問題來自:iOS開發基礎:開發兩年的你也不會寫的Blockapp
// 返回值類型+(^block名)(參數列表) = ^返回值類型(參數列表){...}; NSInteger (^sumBlock)(NSInteger, NSInteger) = ^NSInteger (NSInteger a, NSInteger b) { return a + b; }; NSInteger sum = sumBlock(1, 2); NSLog(@"sum = %@", @(sum));
// 其實和局部變量的聲明是相同的,注意使用copy @property (nonatomic, copy) NSString* (^appendStringBlock)(NSString *title);
相比於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; }];
__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));
- (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