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