首页 > 代码库 > 简单运用block

简单运用block

block是一门有用的大后期学问。现在我只是列出一点基本用法。

 

1.快速枚举(Enumeration)

  通常是和NSArray, NSDictionary, NSSet, NSIndexSet放在一起用。

  当和以上这两种东西放在一起用时,通常block有两种用处。(代码为实例操作)

    i. 第一种block用法是枚举后,对每个枚举对象进行一些操作,block返回值为void

    ii. 第二种枚举对象的index,当然这些枚举对象是通过某些测试后才返回的。

    

// 第一种用法 返回值为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的indexNSArray *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 多线程

  这里就直接举一个例子了。假设我们有一个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



 

国外友人的罗列的基本用法

NSArray

  • enumerateObjectsUsingBlock – Probably the Block method I use the most, it basically is a simpler, cleaner foreach.
  • enumerateObjectsAtIndexes:usingBlock: – Same as enumerateObjectsUsingBlock: except you can enumerate a specific range of items in the array instead of all the items. The range of items to enumerate is passed via the indexSet parameter. // 这里indexes可以用NSMakeRange(0, 3)这种来自我创建 以及+ (id)indexSetWithIndexesInRange:(NSRange)indexRange
  • indexesOfObjectsPassingTest: – The Block returns an indexset of the the objects that pass a test specified by the Block. Useful for looking for a particular group of objects.

NSDictionary

  • enumerateKeysAndObjectsUsingBlock: – Enumerates through a dictionary, passing the Block each key and object.
  • keysOfEntriesPassingTest: – Returns a set of the keys corresponding to objects that pass a test specified by the Block.

UIView

  • animateWithDuration:animations: – UIViewAnimation Block, useful for simple animations.
  • animateWithDuration:completion: – Another UIViewAnimation Block, this version adds a second Block parameter for callback code when the animation code has completed.

Grand Central Dispatch

  • dispatch_async – This is the main function for async GCD code.

简单运用block