十三:block的用法(作為屬性、傳回值和參數),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 @end14 @implementation ViewController15 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 *)event26 {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 ZWPerson13 - (void)eat:(void(^)())block14 {15 NSLog(@"吃美味");16 block();17 }18 @end19 20 ViewController.m檔案中:21 #import "ViewController.h"22 #import "ZWPerson.h"23 @interface ViewController ()24 @property (strong, nonatomic)ZWPerson *p;25 26 @end27 @implementation ViewController28 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 ZWPerson10 - (void (^)())run11 {12 return ^(){13 NSLog(@"跑了3公裡");14 };15 }16 @end17 18 ViewController.m檔案中:19 #import "ZWPerson.h"20 @implementation ZWPerson21 - (void)viewDidLoad {22 [super viewDidLoad];23 ZWPerson *p = [[ZWPerson alloc] init];24 //可以直接通過點文法調用run,如果有參數,()表示裡面可以傳參數,25 p.run();26 }