I have an instance method that I'd like to invoke directly using the callback param from a block in objective-c. I prefer this approach when I need to do more than a simple 1 liner in the callback.
Here is the basic setup...
I init a class w/ some type of call back so I can parse json after the http request lets say
- (void)initFooAndDoStuff {
Foo *foo = [[Foo alloc] initWithCallback:^(NSData * response){
// do stuff
}];
}
//this is the instance method I'd like to invoke instead of an inline function
- (void)callBackWithHttpResponse:(NSData *)response {
// do stuff ... assuming it's more complex than a 1 liner that is
}
I can setup a call back that does something inline (but again more complex stuff would be better in a stand alone instance method perhaps)
Foo *foo = [[Foo alloc] initWithCallback:^(NSData * response){
NSLog(@"foo");
}];
I can use the instance method like below but it feels a little long winded. Any way I can cut this down (the syntax that is).
Foo *foo = [[Foo alloc] initWithCallback:^(NSData * response){
[self callBackWithHttpResponse:response];
}];
Footo work that way.Foomight define- (id) initWithTarget:(id)target callbackSelector:(SEL)selector. It would save thetargetand theselectorin ivars. It would be called like[[Foo alloc] initWithTarget:self callbackSelector:@selector(callBackWithHttpResponse:)]. To call the callback,Foowould do[_target performSelector:_selector withObject:response].