将变量传递给 void ^() 块

Passing variable to void ^() block

我有一个带有回调的方法,看起来像这样:

- (void)doStuff:(void ^())callback
{
    //Do a whole bunch of stuff

    //Perform callback
    callback();
}

稍后我会像这样调用此方法:

[self doStuff:^{[self callbackMethod];}];

当没有数据要传递时,这工作得很好,但现在我有一些数据需要在方法之间传递。

采取以下方法:

- (void)showAViewWithOptions:(int)options

在这个方法中,我显示了一个带有特定选项的视图,但如果屏幕上已经有其他东西,我调用方法隐藏它并回调回这个方法。

所以实现看起来像这样。

- (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
}

编译和运行没有问题,但是options在通过后失去了它的价值。

坦率地说,它的编译令我感到惊讶,因为我认为它不会接受带参数的块。

例如,如果我调用 [self showAViewWithOptions:4];,当触发回调时,options = -1730451212


如何将值 options 绑定到块?或者更好的问题,这根本不可能,因为当我调用回调时:

callback();

我没有在括号中添加任何内容?

如果是这样,那么一个很好的后续问题将是:为什么这甚至首先编译?

这应该有效:

- (void)showAViewWithOptions:(int)options
{
     if(_oldViews != nil)
     {
         [self hideOldView:^(){
             // Recursion doesn't feel right; be careful!
             // Why can't whatever is being done by this call be done
             // within this block?
             [self showAViewWithOptions:options];
         }];
         return;
     }

     //Show the new view
}

具有 return 值和参数的块如下所示:

^ return_type (parameter1_type parameter1_name, parameter2_type parameter2_name, ...) {
do_stuff;
};

您可以将变量传递给方法...您在方法内部调用的回调方法:

- (void)hideOldViewWithId:(float)f callback:(void (^)(float f))callback{
    f = f + 2.0f;
    callback(f);
}

然后调用

[self hideOldViewWithId:1.0f callback:^(float f) {
    NSLog(@"callback with float: %f", f);
}];