有 2 种向主队列分派任务的方法,两者都是异步的,即使在任务没有执行的时候也让你
的程序继续:
dispatch_async function 在分派队列上执行一个 Block Object。
dispatch_async_f function 在分派队列上执行一个 C 函数。
一、dispatch_async function 在分派队列上执行一个 Block Object
Dispatch_sync 方法不能在主队列中调用,因为无限期的阻止线程并会导致你的应用死 锁。所有通过 GCD 提交到主队列的任务必须异步提交。
dispatch_queue_t mainQueue=dispatch_get_main_queue();
dispatch_async(mainQueue, ^{
[[[UIAlertView alloc] initWithTitle:@"GCD"
message:@"GCD is amazing!"
delegate:nil cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil] show];
}) ;
二、dispatch_async_f function 在分派队列上执行一个 C 函数
Dispatch_get_global_queue 函数的第一个参数说明了并发队列的优先级,这个属性 GCD
必须替程序员检索。优先级越高,将提供更多的 CPU Timeslice 来获取该队列执行的代码。
你可以使用下面这些值作为 Dispatch_get_global_queue 函数的第一个参数: DISPATCH_QUEUE_PRIORITY_LOW
您的任务比正常任务用到更少的 Timeslice。
DISPATCH_QUEUE_PRIORITY_DEFAULT
执行代码的默认系统优先级将应用于您的任务。
DISPATCH_QUEUE_PRIORITY_HIGH
和正常任务相比,更多的 Timeslices 会应用到你的任务中。
Dispatch_get_global_queue 函数的第二个参数已经保存了,你只要一直给它输入数值 0就可以了。
dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
size_t numberOfIteration=10;
dispatch_async(queue, ^{
dispatch_apply(numberOfIteration, queue, ^(size_t iteration) {
//
NSLog(@"-----dispatch");
});
});
三、
在 GCD 的帮助下能够异步执行 Non-UI 相关任务
dispatch_queue_t currentQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(currentQueue, ^{
__block UIImage *image=nil;
dispatch_sync(currentQueue, ^{
//download the image here
NSString *urlAsString = @"http://images.apple.com/mobileme/features/images/ipad_findyouripad_20100518.jpg";
NSURLRequest *urlRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlAsString]];
NSError *downloadError=nil;
NSData *imageData=[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];
if (downloadError == nil && imageData != nil){
image = [UIImage imageWithData:imageData]; /* We have the image. We can use it now */
}
else if (downloadError != nil)
{
NSLog(@"Error happened = %@", downloadError);
}
else
{
NSLog(@"No data could get downloaded from the URL.");
}
});
dispatch_sync(dispatch_get_main_queue(), ^{
//show the image to the user here on the main queue
if (image != nil){
/* Create the image view here */
UIImageView *imageView = [[UIImageView alloc]
initWithFrame:self.view.bounds];
/* Set the image */ [imageView setImage:image];
/* Make sure the image is not scaled incorrectly */
[imageView setContentMode:UIViewContentModeScaleAspectFit];
/* Add the image to this view controller's view */ [self.view addSubview:imageView];
} else
{
NSLog(@"Image isn't downloaded. Nothing to display.");
}
});
});