需求:在FirstViewController中点击"接收"按钮接收来自SecondViewController的block传递的值
步骤如下:
1.在SecondViewController .h文件中声明block
1 #import <UIKit/UIKit.h> 2 3 //为要声明的Block重新定义了一个名字myBlock 4 typedef void (^myBlock)(NSString *str);// 一会要传的值为NSString类型 5 6 @interface SecondViewController : UIViewController 7 // 声明block属性 8 @property (nonatomic, copy) myBlock block; 9 // 声明block方法 10 - (void)getStr:(myBlock)block; 11 12 @end
2.在SecondViewController .m文件中实现 - (void)getStr:(myBlock)block方法
1 #import "SecondViewController.h" 2 @interface SecondViewController () 3 4 @end 5 6 @implementation SecondViewController 7 8 - (void)viewDidLoad { 9 [super viewDidLoad]; 10 11 } 12 13 - (void)getStr:(myBlock)block { 14 15 //把传进来的Block块保存实例变量block中(SecondViewController.h中定义的属性) 16 self.block = block; 17 18 //使用block要要确定其不为nil 19 if (self.block != nil) { 20 self.block(@"要传给FirstViewController的字符串"); 21 } 22 } 23 24 @end
3.在FirstViewController.m文件 中接收SecondViewController.m的block传来的值
1 #import "FirstViewController.h" 2 #import "SecondViewController.h" 3 4 @interface FirstViewController () 5 @property (nonatomic, strong) SecondViewController *secondVc; 6 @end 7 8 @implementation FirstViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 13 //先拿到第二个控制器 14 SecondViewController *secondVc = [[SecondViewController alloc]init]; 15 _secondVc = secondVc; 16 17 //添加获取字符串按钮 18 [self addGetStrBtn]; 19 20 } 21 22 - (void)addGetStrBtn { 23 UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(150, 250, 50, 40)]; 24 [self.view addSubview:btn]; 25 [btn setTitle:@"获取" forState:UIControlStateNormal]; 26 btn.backgroundColor = [UIColor redColor]; 27 [btn addTarget:self action:@selector(getStr) forControlEvents:UIControlEventTouchUpInside]; 28 } 29 30 31 - (void)getStr { 32 [_secondVc getStr:^(NSString *str) { 33 NSString *string = str; 34 NSLog(@"从SecondViewController获取的字符串为:%@",string); 35 }]; 36 } 37 38 @end
时间: 2024-10-23 19:21:31