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