2.Block實戰

2.Block實戰

問題來自:iOS開發基礎:開發兩年的你也不會寫的Blockapp

  1. 聲明一個Block,並調用它。
  2. 聲明一個Block型的屬性。
  3. 聲明一個方法,接受一個Block型的參數,並寫出調用時傳入的Block實參。
  4. 實現一個Block的遞歸調用(Block調用本身)。
  5. 實現一個方法,將Block做爲返回值。

1. 聲明block,並使用

// 返回值類型+(^block名)(參數列表) = ^返回值類型(參數列表){...};
NSInteger (^sumBlock)(NSInteger, NSInteger) = ^NSInteger (NSInteger a, NSInteger b) {
    return a + b;
};

NSInteger sum = sumBlock(1, 2);
NSLog(@"sum = %@", @(sum));

2.聲明Block型的屬性

// 其實和局部變量的聲明是相同的,注意使用copy
@property (nonatomic, copy) NSString* (^appendStringBlock)(NSString *title);

3.Block類型的方法參數

相比於Block型的屬性形式,只須要將^後面的block名提到最後便可網站

// 返回值類型(^)(參數列表)block名
- (void)declareAMethodWithBlock:(BOOL(^)(NSInteger index))callBackBlock {
    NSInteger idx = 0;
    while (callBackBlock(idx)) {
        NSLog(@"%@", @(idx));
        idx = idx + 1;
    }
}

// 方法調用
[self declareAMethodWithBlock:^BOOL(NSInteger index) {
    return index < 10;
}];

4.Block遞歸調用

__block NSInteger number = 0;
__block void (^calculateSum) (NSInteger) = ^void (NSInteger input) {
    number = input + 1;
    if (number >= 10) {
        calculateSum = nil;
        return;
    }
    calculateSum(number);
};

calculateSum(1);
NSLog(@"%@", @(number));

5.Block做爲返回值

- (NSInteger (^) (NSInteger))returnBlockType {
    return ^ NSInteger (NSInteger a){
        return  a * a;
    };
}

NSLog(@"%@", @([self returnBlockType](20)));

推薦一個網站

How Do I Declare A Block in Objective-C?,記不住block的時候能夠參考一下atom

相關文章
相關標籤/搜索