I have a method with a callback that looks something like this:
- (void)doStuff:(void ^())callback
{
//Do a whole bunch of stuff
//Perform callback
callback();
}
I would then call this method later on like this:
[self doStuff:^{[self callbackMethod];}];
This works just fine when there is no data to pass, but now I have some data that I need to pass between the methods.
Take the following method:
- (void)showAViewWithOptions:(int)options
In this method, I show a view with certain options, but if there's something else already on the screen, I call the method to hide it with a callback back to this method.
So the implementation looks like this.
- (void)hideOldView:(void ^())callback
{
//Hide all objects in _oldViews and set _oldViews = nil
callback();
}
- (void)showAViewWithOptions:(int)options
{
if(_oldViews != nil)
{
[self hideOldView:^(int options){[self showAViewWithOptions:options];}];
return;
}
//Show the new view
}
This compiles and runs without issue, but options
loses its value after being passed.
Quite frankly, it surprised me that it compiled, since I thought it wouldn't accept a block with arguments.
For instance, if I call [self showAViewWithOptions:4];
, when the callback is fired, options = -1730451212
.
How do I bind the value options
to the block? Or a better question, is this simply not possible because when I call the callback:
callback();
I'm not putting anything into the parentheses?
If so, then a good follow-up question would be: why does this even compile in the first place?