Luke The Obscure
Luke The Obscure

Reputation: 1524

Creating callbacks with blocks

I'm new to Objective-C having come from the JavaScript world, and I'm trying to define a "callback" property on a class. In JavaScript land we're used to passing around functions willy-nilly, but it seems Objective-C isn't so lenient.

Here's how I tried to do it (trying to simplify things as much as possible):

@interface CallbackThing : NSObject
  @property (nonatomic) NSString *derpDerp;
  @property (nonatomic) SEL callback;
@end

Then later in another class....

CallbackThing *testCallbackThing = [CallbackThing alloc] init];
testCallbackThing.callback = @selector(methodInThisCLass);

Finally in another class...

if (self.testCallbackThing.callback != nil){
    [self.thatOtherClass performSelector:self.testCallbackThing.callback];
}

That works great! I was so proud of myself... Until...

"warning: performSelector may cause a leak because its selector is unknown!"

Trying to read up on things, and it seems that the new way to do things is to use blocks... But none of the examples I've looked at make much sense in this scenario.

Upvotes: 0

Views: 341

Answers (1)

Snowman
Snowman

Reputation: 32091

Not sure what your specific use case is, but blocks are easy. First, declare your block type:

typedef void (^MyBlock)(NSArray*, NSString*);

Then you can set this as a property, like you did with SEL:

@property(nonatomic, copy) MyBlock block;

Then, you simply call the block, which executes it:

self.block(someArray, someString);

Upvotes: 2

Related Questions