iOS block传值

一、在第二个控制器的.h文件声明block   (一般命名格式为:控制器名+Block)

@property (nonatomic, copy) void (^SellHouseControllerBlock)(NSString *str);

二、在第二个控制器的.m文件里设置block

if (self.SellHouseControllerBlock) {
        self.SellHouseControllerBlock(@"hehe");
}

三、在第一个控制器里接受传来的值

SellHouseController *newViewController = [[SellHouseController alloc]init];
newViewController.SellHouseControllerBlock = ^(NSString *str){
    NSLog(@"%@",str);
};

 如果要在block使用self时,需要先weakself,否则在block还没执行完毕时就想销毁当前对象(比方说用户关闭了当前页面),这时就会因为block还对self有一个reference而没有立即销毁,这会

 引起很多问题,比方说你写在 - (void)dealloc {} 中的代码并不能马上得到执行。

SellHouseController *newViewController = [[SellHouseController alloc]init];
__weak __typeof(self)weakSelf = self; // 对self获取一个弱引用(也就是refrence count不会加1) newViewController.SellHouseControllerBlock
= ^(NSString *str){
  __strong __typeof(weakSelf)strongSelf = weakSelf; // 避免self在执行过程中变成nil这种情况发生,我们会重新strongify self
[
strongSelf some];
};
原文地址:https://www.cnblogs.com/xsphehe/p/6397523.html