将变量传递给void ^()块

时间:2015-11-12 09:23:03

标签: ios objective-c parameter-passing objective-c-blocks

我有一个带回调的方法,如下所示:

- (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();

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

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

3 个答案:

答案 0 :(得分:3)

这应该有效:

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

你可以将vairable传递给方法...你在方法中调用的回调方法:

- (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);
}];
相关问题