[学习笔记]object c, Grand Central Dispatch的使用

GCD is a C API

The basic idea is that you have queues of operations The operations are specified using blocks.
Most queues run their operations serially (a true “queue”).
We’re only going to talk about serial queues today.

The system runs operations from queues in separate threads Though there is no guarantee about how/when this will happen.
All you know is that your queue’s operations will get run (in order) at some point.
The good thing is that if your operation blocks, only that queue will block.

Other queues (like the main queue, where UI is happening) will continue to run.

So how can we use this to our advantage?
Get blocking activity (e.g. network) out of our user-interface (main) thread. Do time-consuming activity concurrently in another thread. 

Important functions in this C API
Creating and releasing queues

dispatch_queue_t dispatch_queue_create(const char *label, NULL); // serial queue

void dispatch_release(dispatch_queue_t);

Putting blocks in the queue

typedef void (^dispatch_block_t)(void);
void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);

Getting the current or main queue

dispatch_queue_t dispatch_get_current_queue();
void dispatch_queue_retain(dispatch_queue_t); // keep it in the heap until dispatch_release

dispatch_queue_t dispatch_get_main_queue();

What does it look like to call these?
Example ... assume we fetched an image from the network (this would be slow). 

- (void)viewWillAppear:(BOOL)animated
{
NSData *imageData = [NSData dataWithContentsOfURL:networkURL];
UIImage *image = [UIImage imageWithData:imageData];
self.imageView.image = image;
self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
self.scrollView.contentSize = image.size;
}
- (void)viewWillAppear:(BOOL)animated
{
dispatch_queue_t downloadQueue = dispatch_queue_create(“image downloader”, NULL);
dispatch_async(downloadQueue, ^{
NSData *imageData = [NSData dataWithContentsOfURL:networkURL];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:imageData];
self.imageView.image = image;
self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
 self.scrollView.contentSize = image.size;
});
});
dispatch_release(downloadQueue);
}

Don’t worry, it won’t remove the queue from the heap until all blocks have been processed.    




posted @ 2012-01-31 18:00  rickxu  阅读(1510)  评论(0)    收藏  举报