摘自:http://www.cnblogs.com/ltpblog/p/3684127.html
Date : 2015-12-4
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];
};
推薦:
ios block常見的錯誤(三)——并發編程的block引用
文章列表