block的用法(作为属性、返回值和参数)

block在实际开发中简便易用,主要用在回调,控制器之间的传值等方面。那下面对其用法进行分类

直接上代码:(全部用的无参无返回值)

第一种使用方法(作为属性)在当前使用的文件夹中进行赋值和调用

 1 ZWPerson.h文件中:
 2 
 3 #import <Foundation/Foundation.h>
 4 @interface ZWPerson : NSObject
 5 @property (strong, nonatomic)void(^play)();
 6 @end
 7 
 8 ViewController.m文件中:
 9 #import "ViewController.h"
10 #import "ZWPerson.h"
11 @interface ViewController ()
12 @property (strong, nonatomic)ZWPerson *p;
13 @end
14 @implementation ViewController
15 
16 - (void)viewDidLoad {
17     [super viewDidLoad];
18     ZWPerson *p = [[ZWPerson alloc] init];
19     p.play = ^(){
20         NSLog(@"玩游戏");
21     };
22     _p = p;
23 }
24 
25 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
26 {
27     //在当前文件夹中,哪里需要就可以直接调用这个方法
28     _p.play();
29 }
30 @end

第二种使用方法(作为方法参数)主要是外界不能调用,只能在方法内部进行调用,用于回调和传值等

也可以直接在当前文件夹,定义一个方法调用

 1 ZWPerson.h文件中:
 2 
 3 #import <Foundation/Foundation.h>
 4 @interface ZWPerson : NSObject
 5 
 6 - (void)eat:(void(^)()) bolck;
 7 
 8 @end
 9 
10 ZWPerson.m文件中:
11 #import "ZWPerson.h"
12 @implementation ZWPerson
13 - (void)eat:(void(^)())block
14 {
15     NSLog(@"吃美味");
16     block();
17 }
18 @end
19 
20 ViewController.m文件中:
21 #import "ViewController.h"
22 #import "ZWPerson.h"
23 @interface ViewController ()
24 @property (strong, nonatomic)ZWPerson *p;
25 
26 @end
27 @implementation ViewController
28 
29 - (void)viewDidLoad {
30     [super viewDidLoad];
31 
32     ZWPerson *p = [[ZWPerson alloc] init];
33     [p eat:^{
34         NSLog(@"睡觉");
35     }];
36 }
37 @end

第三种使用方法(作为方法返回值)内部不能调用,只能外界调用,相当于代替了方法!

 1 ZWPerson.h文件中:
 2 #import <Foundation/Foundation.h>
 3 @interface ZWPerson : NSObject
 4 - (void(^)())run;
 5 @end
 6 
 7 ZWPerson.m文件中:
 8 #import "ZWPerson.h"
 9 @implementation ZWPerson
10 - (void (^)())run
11 {
12     return ^(){
13         NSLog(@"跑了3公里");
14     };
15 }
16 @end
17 
18 ViewController.m文件中:
19 #import "ZWPerson.h"
20 @implementation ZWPerson
21 - (void)viewDidLoad {
22     [super viewDidLoad];
23     ZWPerson *p = [[ZWPerson alloc] init];
24     //可以直接通过点语法调用run,如果有参数,()表示里面可以传参数,
25     p.run();
26 }
原文地址:https://www.cnblogs.com/hissia/p/5684991.html