//1.什么是block
定义在外部.
(1)在类中,定义一个block变量,就像定义一个函数
(2)block可以定义在方法内部,也可以定义在方法外部;
(3)只有调用block时候,才会执行其{}体内的代码
//下面我们就来看看简单的block传值
1.我们这里用ViewController 和DetailViewController来演示,首先思路是:在
ViewController中有一个button,用来跳转界面的,还有一个label是接收从下一个界面传过来的值.而在
DetailViewController中有一个button,用来返回到上一个界面的,还有一个UItextfield,会将输入的内容传到上一个界面的label中
typedef void(^CallBlock)(NSString *money);
@interface DetailViewController : UIViewController
- (void)getMoneyWithCallBlock:(CallBlock)block;
@end
3.然后在 DetailViewController.m中创建一个block属性
@property (nonatomic,copy) CallBlock callBlock;
4.然后写一个方法将UItextfield的值传出去
self.view.backgroundColor = [UIColor whiteColor];
UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 50, 50)];
[back setTitle:@"返回" forState:UIControlStateNormal];
[back setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
back.backgroundColor = [UIColor blackColor];
[back addTarget:self action:@selector(backTheLastPage) forControlEvents:UIControlEventTouchUpInside];
_textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 150, 100, 30)];
_textField.placeholder = @"请输入内容";
[self.view addSubview:_textField];
[self.view addSubview:back];
- (void)getMoneyWithCallBlock:(CallBlock)block{
self.callBlock = block;
}
- (void)backTheLastPage{
_callBlock(_textField.text );//将textfield的值传出去
[self dismissViewControllerAnimated:YES completion:nil];
}
5.接下来我们就来
ViewController.m中的button方法里面来使用
_label = [[UILabel alloc] initWithFrame:CGRectMake(100, 120, 100, 30)];
_label.text = @"nothing";
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 100, 100)];
[button setTitle:@"下一页" forState:0];
[button addTarget:self action:@selector(enterTheNextPage) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
[self.view addSubview:_label];
- (void)enterTheNextPage{
DetailViewController *detailVC = [[DetailViewController alloc] init];
__weak typeof(self) weakSelf = self;//修改全局属性,避免循环引用
[detailVC getMoneyWithCallBlock:^(NSString *money) {
weakSelf.label.text = money;
NSLog(@"%@",money);
}];
[self presentViewController:detailVC animated:YES completion:nil];
}
总结:当我们需要改变block外部变量的值的时候,为了避免循环引用,我们会给他加上__block修饰符. 使用__block变量的优点是:
1.
通过__block变量可以控制对象的生命周期
2.
在不能使用__weak修饰符的环境中,我们可以避免使用__unsafe_unretained修饰符
3.
在执行Block时可动态地决定是否将nil或者其它对象赋值给__block变量