iOS學習之代碼塊(Block)

來源:互聯網
上載者:User

標籤:ssi   mic   自訂   ++   通過   int   atomic   學習   void   

代碼塊(Block)

(1)主要作用:將一段代碼儲存起來,在需要的地方調用即可。

(2)全域變數在代碼塊中的使用

全域變數可以在代碼塊中使用,同時也可以被改變,程式碼片段如下:

1 int local = 1;//注意:全域變數2 void (^block0)(void) = ^(void){3     local ++;4     NSLog(@"local = %d",local);5 };    6 block0();7 NSLog(@"外部 local = %d",local);

結果為:local = 2;

外部 local = 2;

(3)局部變數在代碼塊中的使用

**一般的局部變數只能在代碼塊中使用,但不能被改變(此時無法通過編譯),程式碼片段如下:

1 int n = 1000;//局部變數2 void (^block1)(void) = ^(void){3 //  n++;4     NSLog(@"float1 = %d",n);5 };6 block1();7 NSLog(@"float2 = %d",n);

結果為:float1 = 1000

float2 = 1000

**將局部變數聲明為__block時,不僅可以在代碼塊中使用,同時也可以被改變。程式碼片段如下:

1 __block int j = 200;//聲明為__block變數2 void (^block2)(void) = ^(void){3     j++;4     NSLog(@"塊變數 = %d",j);5 };6 block2();7 NSLog(@"快變數2 = %d",j);

結果為:塊變數 = 201

快變數2 = 201

(4)代碼塊作為方法參數使用

自訂類:

首先BlockClasss.h類:

 1 #import <Foundation/Foundation.h> 2  3 @interface BlockClasss : NSObject 4  5 //聲明int型變數 6 @property (nonatomic,assign)int result; 7 @property (nonatomic,assign)int result2; 8  9 - (int)result:(int (^)(int))block;10 11 - (BlockClasss *(^)(int value))add;12 @end

然後BlockClasss.m的實現:

 1 #import "BlockClasss.h" 2  3 @implementation BlockClasss 4 - (int)result:(int (^)(int))block{ 5     _result = block(_result); 6     return _result; 7 } 8  9 - (BlockClasss *(^)(int))add{10     return ^BlockClasss *(int value){11         _result2 += value;12         return self;13     };14 }15 @end

代碼塊作為方法參數的使用代碼:

1 BlockClasss *bl = [[BlockClasss alloc]init];2 [bl result:^int(int result) {3     result += 10;4     result *= 2;5     return  result;6 }];7 NSLog(@"result = %d",bl.result);

結果為:result = 20

(5)代碼塊作為方法傳回值使用:

1 BlockClasss *bl2 = [[BlockClasss alloc]init];2 bl2.add(100).add(200);3 NSLog(@"結果 ^=%d",bl2.result2);

列印結果為:結果 ^=300

(6)避免循環參考

在代碼塊中不能使用self或者_XXX,以免發生循環參考。最好是將self在外部定義為__weak屬性,然後再去使用。

例如:

1 __weak self weakSelf = self;2 _block = ^{3     NSLog(weakSelf.result);4 };

 

iOS學習之代碼塊(Block)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.