iOS GCD(9)
NSArray *array = [[NSArray alloc] initWithObjects:@"string1",@"string2",@"string3", nil];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t index){
NSLog(@"%zu : %@",index,[array objectAtIndex:index]);
});
//假如对一个NSArray类对象的所有元素执行处理时,不必一个个编写for循环
NSArray *array = [[NSArray alloc] initWithObjects:@"string1",@"string2",@"string3", nil];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t index){
NSLog(@"%zu : %@",index,[array objectAtIndex:index]);
});
由于dispatch_apply方法也与dispatch_sync方法相同,会等待处理执行结束,因此推荐在dispatch_async函数中非同步的执行dispatch_apply方法。
例如:
[cpp]
NSArray *array = [[NSArray alloc] initWithObjects:@"string1",@"string2",@"string3", nil];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//在Glocbal Dispatch Queue中非同步执行
dispatch_async(queue, ^{
//等待dispatch_apply方法中的全部处理执行结束
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t index){
NSLog(@"%zu : %@",index,[array objectAtIndex:index]);
});
//dispatch_apply方法中的全部处理任务执行结束
dispatch_async(dispatch_get_main_queue(), ^{
//在主线程中执行处理
NSLog(@"done");
});
});
NSArray *array = [[NSArray alloc] initWithObjects:@"string1",@"string2",@"string3", nil];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
相关新闻>>
- 发表评论
-
- 最新评论 更多>>