GCD部分用法及遍历方法

2017-01-06  本文已影响9人  seventhboy

GCD
Dispatch_group:(异步执行,dispatch_group_notify监听group执行完毕之后执行)

dispatch_group_t downloadGroup = dispatch_group_create(); for (int i = 1 ; i <= pageNum; i++) { dispatch_group_enter(downloadGroup); // 执行下载任务 dispatch_group_leave(downloadGroup); } dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{ [activitingArray sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]]]; [self.activeCV reloadData]; });

Dispatch_after:延迟执行dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); // 1 dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // 主线程执行更新动作。});

Dispatch_once:以线程安全的方式执行且仅执行其代码块一次static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedPhotoManager = [[PhotoManager alloc] init]; sharedPhotoManager->_photosArray = [NSMutableArray array]; sharedPhotoManager->_concurrentQueue = dispatch_queue_create(" ", DISPATCH_QUEUE_CONCURRENT); });

Dispatch_apply:并发执行不同迭代,相当于一个for循环,同步的。dispatch_apply(3, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(size_t i) { NSURL *url; switch (i) { case 0: url = [NSURL URLWithString:edGirlfriendURLSting]; break; default: break; }

遍历方法

Dispatch_apply:异步执行,可以利用多核优势
EnumerateObjecsWithOptions:异步执行,多核优势,可以指定遍历顺序[imageArray enumerateObjectsWithOptions:NSEnumerationReverseusingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"idx = %ld, id = %@", idx, obj); }];

EnumerateObjecsUsingBlock:不可指定遍历顺序[imageArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"idx = %ld, id = %@", idx, obj); }];

For in (NSFastEnumeration):快速遍历

对于集合中对象数很多的情况下,for in (NSFastEnumeration)的遍历速度非常之快,但小规模的遍历并不明显(还没普通for循环快)

使用kvc集合运算符运算很大规模的集合时,效率明显下降(100万的数组离谱的21秒多),同时占用了大量内存和cpu

enumerateObjectsWithOptions(NSEnumerationConcurrent)dispatch_apply(Concurrent)的遍历执行可以利用到多核cpu的优势(实验中在双核cpu上效率基本上x2)

遍历执行Block对于耗时的任务来说是很值得这么做的,而且在以后cpu升级成更多核心后不用改代码也可以享受带来的好处

上一篇下一篇

猜你喜欢

热点阅读