Object-c中block需要注意的几点问题
1. Block定义
1) 说明:
int i = 10;
void(^myBlock)() = ^{
NSLog(@"%d", i);
};
i = 100;
myBlock();
BOOL flag = NO;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([@"王五" isEqualToString:obj] || idx == stopIndex) {
*stop = YES;
flag = YES; // 编译错误!!!
}
}];
NSString *stopName = @"王五";
NSArray *array = @[@"张三", @"李四", @"王五", @"赵六"];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"第 %d 项内容是 %@", (int)idx, obj);
if ([stopName isEqualToString:obj] || idx == stopIndex) {
*stop = YES;
}
}];
注意:
@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被释放");
}
__weak DemoObj *weakSelf = self;
int(^sum)(int, int) = ^(int x, int y) {
return [weakSelf sum:x y:y];
};