Objective-C類定義了一個將數據與相關行為相結合的對象。 有時,僅表示單個任務或行為單元而不是方法集合是有意義的。
塊是C,Objective-C和C++等編程語言中的高級功能,它允許創建不同的代碼段,這些代碼段可以傳遞給方法或函數,就像它們是值一樣。 塊是Objective-C對象,因此它們可以添加到NSArray
或NSDictionary
等集合中。 它們還能夠從封閉範圍中捕獲值,使其類似於其他編程語言中的閉包或lambda
。
簡單塊聲明語法
returntype (^blockName)(argumentType);
簡單的塊實現 -
returntype (^blockName)(argumentType)= ^{
};
下麵是一個簡單的示例代碼 -
void (^simpleBlock)(void) = ^{
NSLog(@"This is a block");
};
調用上面塊的示例代碼 -
simpleBlock();
塊接受參數和返回值
塊也可以像方法和函數一樣獲取參數和返回值。
下麵是一個使用參數和返回值實現和調用塊的簡單示例。
double (^multiplyTwoValues)(double, double) =
^(double firstValue, double secondValue) {
return firstValue * secondValue;
};
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);
使用類型定義塊
這是一個在塊中使用typedef
的簡單示例。 請注意,此示例不適用於線上編譯器。 它是使用XCode運行的。
#import <Foundation/Foundation.h>
typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end
@implementation SampleClass
- (void)performActionWithCompletion:(CompletionBlock)completionBlock {
NSLog(@"Action Performed");
completionBlock();
}
@end
int main() {
/* 第一個Objective-C程式 */
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass performActionWithCompletion:^{
NSLog(@"Completion is called to intimate action is performed.");
}];
return 0;
}
執行上面示例代碼,得到以下結果:
2018-11-10 08:14:57.105 demo[184:323] Action Performed
2018-11-10 08:14:57.108 demo[184:323] Completion is called to intimate action is performed.
塊在iOS應用程式和Mac OS X中使用得更多。因此,瞭解塊的用法更為重要。
上一篇:
Objective-C函數
下一篇:
Objective-C數字