block是一门有用的大后期学问。如今我只是列出一点基本用法。html
1.快速枚举(Enumeration)ios
一般是和NSArray, NSDictionary, NSSet, NSIndexSet放在一块儿用。json
当和以上这两种东西放在一块儿用时,一般block有两种用处。(代码为实例操做)多线程
i. 第一种block用法是枚举后,对每一个枚举对象进行一些操做,block返回值为voidapp
ii. 第二种枚举对象的index,固然这些枚举对象是经过某些测试后才返回的。iview
// 第一种用法 返回值为0,对每个对象进行相应操做 NSArray *array = [NSArray arrayWithObjects:@"one", @"two", @"three", nil]; NSMutableArray *mArray = [NSMutableArray alloc]init]; [array enumerateObjectsWithOptions:NSEnumerationConcurrent | NSEnumerationRevese usingBlock:^(id obj, NSUInteger idx, BOOL *stop){ [mArray addObject:obj]; }]; // 第二种用法,返回的是一个经过passTest的index NSArray *array = [NSArray arrayWithObjects:@"one", @"two", @"three", nil]; NSInteger * index = [array indexOfObjectWithOptions:NSEnumerationConcurrent passingTest: (BOOL)^(id obj, NSUInteger idx, BOOL *stop){ NSString *string = (NSString *)obj; return [string hasPrefix:@"O"]; }];
2.GCD 多线程async
这里就直接举一个例子了。假设咱们有一个UILable,如今NSJSONSerialization 来解析某个某个地址的json file。如今要实现的是用这个UILable来表示载入状态,如载入前它的text属性应该是@"is loading", 载入后是@"has loaded" 具体的看代码测试
//在该UILable的viewController的ViewDidAppear 中 statusLable.text = @"is loading"; dispatch_queue_t qq = dispatch_queue_create("com.sayALittle', nil); // 即便你使用了ARC,也记得须要本身写一个dealloc方法来释放queue,可是这里面就不须要用[super dealloc] dispatch_async(queue, ^{ NSError *error; //假设本地有个array用来接收JSON解析出来的Array self.array = [NSJONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:someURL options:kNilOptions error:&error]; dispatch_async(dispatch_get_main_queue(), ^{ statusLable.text = @"has loaded"; }); }); - (void)dealloc { dispatch_release(queue); } //由于UI的事情一直都是在主线程内完成的,因此这里就在解析数据后,立刻在主线程中更新了。 //如前面说的,要一个dealloc来释放queue
国外友人的罗列的基本用法ui
NSArraythis
NSDictionary
UIView
Grand Central Dispatch
转 : http://www.cnblogs.com/davidxie/archive/2012/08/23/2652214.html