一.Block定义
(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; };
二.Block使用
<span style="font-size:18px;">NSArray *array= @[@"张三",@"李四",@"王五",@"赵六"]; [array enumerateObjectsUsingBlock:^(id obj, NSUIntegeridx, BOOL*stop) { NSLog(@"第 %d 项内容是 %@",(int)idx, obj); if ([@"王五"isEqualToString:obj]) { *stop = YES; } }];</span>
NSString *stopName =@"王五"; NSArray *array= @[@"张三",@"李四",@"王五",@"赵六"]; [array enumerateObjectsUsingBlock:^(idobj, NSUInteger idx,BOOL *stop) { NSLog(@"第 %d 项内容是 %@",(int)idx, obj); if ([stopName isEqualToString:obj] || idx == stopIndex) { *stop = YES; } }];
<span style="font-size:18px;">intstopIndex = 1; NSArray *array = @[@"张三", @"李四", @"王五", @"赵六"]; [arrayenumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"第 %d 项内容是 %@", (int)idx, obj); if ([@"王五" isEqualToString:obj] || idx == stopIndex) { *stop = YES; } }];</span>
<span style="font-size:18px;">BOOL flag = NO; [arrayenumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if([@"王五" isEqualToString:obj] || idx == stopIndex) { *stop = YES; flag = YES; // 编译错误!!! } }];</span>
<span style="font-size:18px;">__block BOOL flag = NO; [arrayenumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if([@"王五" isEqualToString:obj] || idx == stopIndex) { *stop = YES; flag = YES; // 现在可以修改了!!! } }];</span>
<span style="font-size:18px;">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));</span>
<span style="font-size:18px;">#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);</span>
@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)对象被添加到数组中,会被数组强引用
问题解决:
局部变量默认都是强引用的,离开其所在的作用域之后就会被释放,使用__weak关键字,可以将局部变量声明为弱引用
__weak DemoObj *weakSelf =self;
int(^sum)(int, int) = ^(int x, int y) { return [weakSelf sum:x y:y]; };
2.7 Block在iOS中使用场景
(6)多线程等等...
原文地址:http://blog.csdn.net/w1396037340/article/details/41985305