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 }
