我想在一个block里对一个成员变量赋值,但是提示“ use of undeclared identifier self"错误,
请问这是怎么回事?
代码如下:
void (^successBlock)(id ) = ^(id responseObject){
NSLog(@"responseObject:%@",responseObject);
NSInteger result = [[responseObject objectForKey:@"result"]integerValue];
if(result == 1){
self.missionsArr= [[responseObject objectForKey:@"data"]objectForKey:@"list"];
}else if (result == 0){
NSLog(@"0");
}
};
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
等了一天没人回答...首先说一下,我不是很能解释的清楚为什么不能在block里调用self变量。但是我遇到这种情况知道怎么可以调用self的变量。
@weakify(self);void (^successBlock)(id ) = ^(id responseObject){ NSLog(@"responseObject:%@",responseObject); NSInteger result = [[responseObject objectForKey:@"result"]integerValue]; if(result == 1){ @strongify(self); self.missionsArr= [[responseObject objectForKey:@"data"]objectForKey:@"list"]; }else if (result == 0){ NSLog(@"0"); } }加一个weakify和strongify这个应该就可以解决问题了,希望楼下的回答能顺便解释以下为什么block不能回调。我大概是明白但是我解释不清楚...
如果还没有解决可以给我留言说一声,因为我这样用基本上就解决了。
不是block的问题 看你的错误信息 想是在类方法中调用了这部分代码 方便的话把多贴点代码
另外关于block的知识 推荐你看下http://www.devtang.com/blog/2013/07/28/a-look-inside-blocks/
楼上的回答是为了防止retain cycle
同意楼上,block里最好不要直接用self,最好在外面__weak typeOf(& *self)weakSelf = self;
之后在block里用weakSelf就行了。防止循环引用。
同意楼上,你看到的@weakify应该是__weak的宏定义,原因楼上说的很清楚