块的引用传递

Pass by reference for blocks

有没有办法通过引用传递块? 下面的代码打印出 "Block is 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");
    };
}

是的,你可以做到。声明类型:

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");}