1 #import "FristViewController.h"
2 #import "AppDateSource.h"
3 @interface FristViewController ()
4 @property(nonatomic,strong)UILabel *showTextLabel;
5 @end
6
7 @implementation FristViewController
8
9 - (void)viewDidLoad {
10 [super viewDidLoad];
11 // Do any additional setup after loading the view.
12 UILabel *showTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 150, 50)];
13 showTextLabel.text = @"帅哥美女";
14 showTextLabel.backgroundColor = [UIColor yellowColor];
15 showTextLabel.textAlignment = NSTextAlignmentCenter;
16 [self.view addSubview:showTextLabel];
17 UIButton *sendMesssageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
18 sendMesssageBtn.backgroundColor = [UIColor yellowColor];
19 [sendMesssageBtn setTitle:@"发送" forState:UIControlStateNormal];
20 sendMesssageBtn.frame = CGRectMake(100, 300, 150, 50);
21 [sendMesssageBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
22 [sendMesssageBtn addTarget:self action:@selector(sendMesssageAction) forControlEvents:UIControlEventTouchUpInside];
23 [self.view addSubview:sendMesssageBtn];
24 self.showTextLabel = showTextLabel;
25
26 }
27 -(void)sendMesssageAction
28 {
29 #warning 第四步:block回调,即实现block
30 AppDateSource *dataBlock = [[AppDateSource alloc] init];
31 //调用方法,实现Block作为方法参数
32 [dataBlock sendMessage:@10086 andBlock:^(NSString *stirng) {
33 self.showTextLabel.text = stirng;
34 }];
35
36 //总结:Block作为方法参数传值应用场景:一般是在处理数据的Model层进行使用;具体步骤:
37 //1.对Block进行typedef
38 //2.声明方法是Block作为方法参数
39 //3.实现声明的方法,将要传递的内容传递出去
40 //4.实现Block的回调
41 }
1 #import <Foundation/Foundation.h>
2 #warning 第一步:Block的重定义typedef
3 typedef void(^AppDateSourceBlock)(NSString *stirng);
4 @interface AppDateSource : NSObject
5 #warning 第二步:声明方法,让Block作为方法参数
6 -(void)sendMessage:(NSNumber *)number andBlock:(AppDateSourceBlock)block;
7 @end
1 #import "AppDateSource.h"
2
3 @implementation AppDateSource
4 #warning 第三步:实现Block作为方法参数的那个方法
5 -(void)sendMessage:(NSNumber *)number andBlock:(AppDateSourceBlock)block
6 {
7 NSString *string = [NSString stringWithFormat:@"%ld",[number integerValue]];
8 block(string);
9
10 }
11 @end