block 很重要,js中闭包
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"A",@"b",@"B",@"c",@"C", nil];
[dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([@"B" isEqualToString:key]) {
NSLog(@"stoped");
*stop = YES;
}
NSLog(@"value for key %@ is %@",key, obj);
}];
}
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
double stopValue = 14.0;
__block BOOL outSideBool = NO;// 不能在block中修改外部数值除非设置__block
NSNumber *doubleNumber = [NSNumber numberWithDouble:14.0];
NSLog(@"outside value %@", outSideBool?@"yes":@"no");
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:doubleNumber,@"stopValue",@"a",@"A",@"b",@"B",@"c",@"C", nil];
[dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
// NSLog(@"--%@",obj); 字典时无序的,所以不一定会在第一个就stop下来
if ([@"BX" isEqualToString:key] || ([obj doubleValue] == stopValue)) {
NSLog(@"stoped");
*stop = YES;
outSideBool = YES;
}
NSLog(@"value for key %@ is %@",key, obj);
}];
NSLog(@"outside value %@", outSideBool?@"yes":@"no");
}
return 0;
}
有返回值
NSSet *set = ...;
NSSet *matchs = [set objectsPassingTest:^BOOL(id obj,...){
return [obj isKindOfClass:[UIView class]];
}];
简写:
如果没有参数 [UIView animateWithDuration:5.0 animations:^{
view.opacity = 0.5;
}];
NSSet *set = ...;
NSSet *matchs = [set objectsPassingTest:^(id obj,...){ // 从返回值可以明确是bool可以省去bool
return [obj isKindOfClass:[UIView class]];
}];
block可以被存储,放在数组,字典中。。。
循环计数的问题:
NSMutablArray *blocks = ...;
[self.blocks addObject:^{
[self doSomething]; // 这样引用就会出问题,self指向block,block又指向self,
}];
解决:
NSMutablArray *blocks = ...;
__weak MyClass *weakSelf = self; // even though self is strong,weakSelf is weak
[self.blocks addObject:^{
[weakSelf doSomething]; // 这样引用就会出问题,self指向block,block又指向self,
}];
使用:
常用语枚举,上面的字典,
动画中
排序
通知
错误处理
处理完成程序: 设定一个block,当一个需要一点时间的任务完成后,调用block。临时保存
!多线程
block 简单使用
最新推荐文章于 2021-05-22 19:12:44 发布