iOS Block淺析

來源:互聯網
上載者:User

標籤:

Block 的使用有兩種:1.獨立Block 。2.內聯Block 。  《一》獨立Block 使用方式  一、定義一個Block Object,並調用。  1.定義 
// 定義一個Block Object,傳回值:NSString;別名:intToString;參數:NSUInteger。NSString* (^intToString)(NSUInteger) = ^(NSUInteger paramInteger){    NSString *result = [NSString stringWithFormat:@"%lu",(unsignedlong)paramInteger];    return result;};
  2.調用 
// 調用我們定義的Block OjbectNSString *string = intToString(10);NSLog(@"string = %@", string);
  二、將Block Object 當作參數,在方法之間傳遞,調用。 有時候,我們希望將定義的Block Object作為函數的參數使用,就像其他的資料類型一樣。  1.為Block Object 定義簽名 
typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);
這就告訴,編譯器,我們定義了一個簽名(別名)為IntToStringConverter 的Block Object。這個Block傳回值為:NSString;參數為:NSUInteger。  2.定義使用Block為參數的函數 
- (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{    return paramBlockObject(paramInteger);}
這一步,很簡單,我們將前面定義的Block作為了一種類型。這種類型為:IntToStringConverter  3.調用使用Block為參數的方法 
 NSString *result = [self convertIntToString:123 usingBlockObject:intToString];    NSLog(@"result = %@", result);
調用時,123,和intToString可理解為實參。  《二》內聯Block 使用方式 在此之前,讓我們梳理一下需要的代碼:  1.定義
typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);

 

2.用Block作為參數的函數
- (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{    return paramBlockObject(paramInteger);}

 

3.內聯調用
- (void) doTheConversion{    IntToStringConverter inlineConverter = ^(NSUInteger paramInteger){        NSString *result = [NSString stringWithFormat:@"%lu", (unsignedlong)paramInteger];        return result;    };        NSString *result = [self convertIntToString:123usingBlockObject:inlineConverter];    NSLog(@"result = %@", result);    }

 

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.