1.block传值回来
//block 第一步,id为返回类型,无则为void
@property (nonatomic ,copy)id(^titleblock)();
//block 第二步,在哪里调用block
if (_titleblock) {
titleLabel.text = _titleblock();
}
//block 第三步,调用具体方法
CellViewController *cellCtrl = [[CellViewController alloc]init];
NSInteger i = indexPath.row;
NSDictionary *dict = dataManager.taskArray[i];
cellCtrl.titleblock = ^id(){
return [dict objectForKey:@"title"];
};
2.block传值过去
//block 第一步,NSString *str为参数
@property (nonatomic ,copy)void(^block)(NSString *str);
//block 第二步,在哪里调用block
if (_block) {
_block(symbol.data);
}
//block 第三步,调用具体方法
CellViewController *cellCtrl = [[CellViewController alloc]init];
NSInteger i = indexPath.row;
NSDictionary *dict = dataManager.taskArray[i];
cellCtrl.titleblock = ^(NSString *str){
firstVC.label .text = str;
};
注意⚠️!!!
1.想要block判空时不为NULL,block必须先调用,即在第三步时,block的实现方法要先于跳转页面(跳转到block所在的页面)的方法运行,才能保证block是在同一个ViewController内的值
2.block中要用到self时需要注意
Apple 官方的建议是,传进 Block 之前,把 ‘self’ 转换成 weak automatic 的变量,这样在 Block 中就不会出现对 self 的强引用。如果在 Block 执行完成之前,self 被释放了,weakSelf 也会变为 nil
如下:
__weak typeof(self) weakSelf = self;
scanner.block = ^(NSString *str){
DIDStr = str;
[weakSelf.LocalSDKWebView reload];
};
也可以把方法引到外面写,如下:
__weak typeof(self) weakSelf = self;
scanner.block = ^(NSString *str){
__strong __typeof(self) strongSelf = weakSelf;
[strongSelf did:str];
[strongSelf did1];
};
- (void)did:(NSString *)str {
}
- (void)did1 {
}
在 did:str 中,weakSelf 不会变成 nil,不过在 did:str 执行完成,调用第二个方法 did1 的时候,weakSelf 有可能被释放,于是,strongSelf 就派上用场了:
__strong 确保在 Block 内,strongSelf 不会被释放。