2.Block實戰
問題來自:iOS開發基礎:開發兩年的你也不會寫的Block
- 宣告一個Block,并呼叫它,
- 宣告一個Block型的屬性,
- 宣告一個方法,接受一個Block型的引數,并寫出呼叫時傳入的Block實參,
- 實作一個Block的遞回呼叫(Block呼叫自己),
- 實作一個方法,將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的時候可以參考一下
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/229038.html
標籤:iOS
