十三:block的用法(作為屬性、傳回值和參數),block傳回值

來源:互聯網
上載者:User

十三: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 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.