通过引用传递块

时间:2015-05-06 15:52:13

标签: objective-c-blocks

有没有办法通过引用传递块? 下面的代码打印出来" Block是nil"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    void (^block)(void) = nil;
    [self assignBlock:block];

    if ( block ) {block();}
    else{NSLog(@"Block is nil");}

    return YES;
}

- (void)assignBlock:(void (^)(void))blockToAssign
{
    blockToAssign = ^(void){
        NSLog(@"Block assigned");
    };
}

1 个答案:

答案 0 :(得分:1)

是的,你可以这样做。声明一个类型:

typedef void (^MyBlock)();

重新定义接收指针的函数assignBlock:

- (void)assignBlock:(MyBlock *)blockToAssign
{
    // assign the object pointing, not the pointer
    *blockToAssign = ^(void){
        NSLog(@"Block assigned");
    };
}

现在使用类型

初始化块
MyBlock block = nil;

当你调用函数时,传递块的地址:

[self assignBlock:&block];

if ( block ) {block();}
else{NSLog(@"Block is nil");}