block 常用于反向传值
声明
返回值类型 (^block)(参数列表)
调用
闭包的名字=^(参数列表){};
闭包的名字();
如:
void(^aaaaa)(int num,NSString *Sring);
aaaaa=^(int num,NSString *string){
NSLog(@"%d,%@",num,string);
};
aaaaa(120,@“www");
block实现反向传值
(1)用属性实现:
1.在.h文件声明:@property(nonatomic,copy)void(^block)(NSString * Nametexts);
2.在.m文件声明block的值:-(void)back:(UIButton *)sender{
self.block (sender.titleLabel.text);
[self dismissViewControllerAnimated:YES completion:nil];
}
3.在另一个ViewController.m中导入第一步的.h文件,之后:-(void)gonext{
nextViewController *next = [[nextViewController alloc]init];
next.block =^(NSString * Nametexts){
label.text =Nametexts;
};
[self presentViewController:next animated:YES completion:nil];
(2)用方法实现:1.在ViewController1.h 声明方
法:-(void)tou:(void(^)(NSString *message))block;
2.在ViewController1.m 调用这个方法:-(void)tou:(void(^)(NSString *message))block{
block(@"大黄牛");
}
3.在ViewController.m中导入ViewController1.h 之后在- (void)viewDidLoad 输入:ViewController1 *v1 = [[ViewController1 alloc]init];
[v1 tou:^(NSString *message) {
NSLog(@"%@",message);
}];
注意:1.修改Block外部变量的时候 需添加__block 修饰。
如:__block UIImage *image = nil;
imageNameBlock =^(NSString *imageName){
image = [UIImage imageNamed:imageName];
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
};
imageNameBlock (@"头像.jpg");
2.声明的 block为 全局变量时
block会被循环引用 因此要用 __weak 弱引用
例: __weak ViewController *vis = self;
__block UIImage *image = nil;
imageNameBlock =^(NSString *imageName){
image = [UIImage imageNamed:imageName];
vis.view.backgroundColor = [UIColor colorWithPatternImage:image];