一.Block定義
1.1定義1.2示例代碼(1)Block是OC中的一種數據類型,在iOS開發中被廣泛使用
(2)^是Block的特有標記
(3)Block的實現代碼包含在{}之間
(4)大多情況下,以內聯inline函數的方式被定義和使用
(5)Block與C語言的函數指針有些相似,但使用起來更加靈活
void(^demoBlock)() =^ { NSLog(@"demo"); }; int(^addBlock)(int, int) =^(int x, int y) { return x +y; };說明: (1)(返回類型)(^塊名稱)(參數類型)=^(參數列表){代碼實現}; (2)如果沒有參數,等號後面參數列表的()可以省略
二.Block使用
NSArray *array= @[@"張三",@"李四",@"王五",@"趙六"]; [array enumerateObjectsUsingBlock:^(id obj, NSUIntegeridx, BOOL*stop) { NSLog(@"第 %d 項內容是 %@",(int)idx, obj); if ([@"王五"isEqualToString:obj]) { *stop = YES; } }];
NSString *stopName =@"王五"; NSArray *array= @[@"張三",@"李四",@"王五",@"趙六"]; [array enumerateObjectsUsingBlock:^(idobj, NSUInteger idx,BOOL *stop) { NSLog(@"第 %d 項內容是 %@",(int)idx, obj); if ([stopName isEqualToString:obj] || idx == stopIndex) { *stop = YES; } }];
intstopIndex = 1; NSArray *array = @[@"張三", @"李四", @"王五", @"趙六"]; [arrayenumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"第 %d 項內容是 %@", (int)idx, obj); if ([@"王五" isEqualToString:obj] || idx == stopIndex) { *stop = YES; } }];
BOOL flag = NO; [arrayenumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if([@"王五" isEqualToString:obj] || idx == stopIndex) { *stop = YES; flag = YES; // 編譯錯誤!!! } }];
__block BOOL flag = NO; [arrayenumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if([@"王五" isEqualToString:obj] || idx == stopIndex) { *stop = YES; flag = YES; // 現在可以修改了!!! } }];
typedef double(^MyBlock)(double, double); MyBlock area = ^(double x, double y) { return x * y; }; MyBlock sum = ^(double a, double b) { return a + b; }; NSLog(@"%.2f", area(10.0, 20.0)); NSLog(@"%.2f", sum(10.0, 20.0));
#pragma mark 定義並添加到數組 @property (nonatomic, strong) NSMutableArray *myBlocks; int(^sum)(int, int) =^(int x, int y) { return [self sum:x y:y]; }; [self.myBlocks addObject:sum]; int(^area)(int, int) =^(int x, int y) { return [self area:x y:y]; }; [self.myBlocks addObject:area]; #pragma mark 調用保存在數組中的Block int(^func)(int, int) = self.myBlocks[index]; return func(x,y);
@property(nonatomic, strong) NSMutableArray *myBlocks; #pragma mark 將代碼改為調用self的方法 int(^sum)(int, int) = ^(int x, int y) { return [self sum:x y:y]; }; [self.myBlocks addObject:sum]; #pragma mark 對象被釋放時自動調用 - (void)dealloc { NSLog(@"DemoObj被釋放"); }說明:
上面的代碼出現的問題,循環引用的結果就是對象無法被釋放!
(1)self對myBlocks的強引用
(2)sum對self的強引用
(3)對象被添加到數組中,會被數組強引用
<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+zsrM4r3ivvY6PC9wPgo8cD6+1rK/seTBv8SsyM+2vMrHx7/S/dPDtcSjrMDrv6rG5Mv51Nq1xNf308PT8tauuvO+zbvhsbvKzbfFLMq508NfX3dlYWu52Lz819ajrL/J0tS9q77Wsr+x5MG/yfnD986qyPXS/dPDPC9wPgo8cD48cHJlIGNsYXNzPQ=="brush:java;"> __weak DemoObj *weakSelf =self;
int(^sum)(int, int) = ^(int x, int y) { return [weakSelf sum:x y:y]; };
2.7 Block在iOS中使用場景
(1)遍歷數組或者字典(6)多線程等等...