swalkner
swalkner

Reputation: 17339

Objective-C: What's the difference between id and an opaque pointer id?

To an id-variable, I can assign a block and call it afterwards; with an opaque pointer id this doesn't work (EXC_BAD_ACCESS).

In RestKit, the userData-object is an "opaque pointer"; now, I'd like to assign a block variable to it to call this block after the request finished. But because of this EXC_BAD_ACCESS it doesn't work. Is there a chance to user this opaque pointer to assign a block to it?

Thanks a lot!

EDIT:

// this works
id testId = ^{
   NSLog(@"hello");
};

testId();

// this doesn't - but it's important to know RestKit
void (^postNotification)(void) = objectLoader.userData // EXC_BAD_ACCESS
postNotification();

objectLoader is of type RKObjectLoader (subclass of RKRequest), and the API says about userData: An opaque pointer to associate user defined data with the request.

Upvotes: 0

Views: 397

Answers (1)

rob mayoff
rob mayoff

Reputation: 385640

You need to show us how you're creating the block and assigning it to userData to be sure, but my guess is you're not copying the block and it's going out of scope, like this:

objectLoader.userData = ^{ ... };

A blocks are created on the stack. That means when the compound statement (e.g. function) enclosing it ends, the block is no longer valid. If you want the block to survive, you need to copy it to the heap:

objectLoader.userData = [^{ ... } copy];

Upvotes: 2

Related Questions