Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

objective c - dispatch_get_global_queue vs dispatch_get_main_queue

Starting to learn about core data and dispatch_async. There is a block of code to get url of image from set of data and set it to model of core data like below

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                NSString *urlString = [[[photoDictionary valueForKey:@"images"] objectAtIndex:0] valueForKey:@"url"];
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [photoModel setValue:imageData forKey:@"photoImageData"];

Can somebody explain to me why we use dispatch_get_global_queue for the outer dispatch_async and dispatch_get_main_queue for inner dispatch_async.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The dispatch_get_global_queue (DispatchQueue.global() in Swift) gets you a background queue upon which you can dispatch background tasks that are run asynchronously (i.e. won't block your user interface). And if you end up submitting multiple blocks to the global queues, these jobs can operate concurrently. If you have multiple blocks of code that you want to submit to a background queue that you must have run sequentially in the background (not often needed), you could create your own serial background queue and dispatch to that, but if concurrent background operations are acceptable, then availing yourself of dispatch_get_global_queue is convenient/efficient.

Be aware, though, that you're not allowed to perform user interface updates in the background queue, so the dispatch_async to the dispatch_get_main_queue (i.e. DispatchQueue.main.async { ... } in Swift) lets that background queue dispatch the user interface updates back to the main queue, once the main queue is available.

This is a very common programming pattern: Submit something to run in the background and when it needs to perform user updates, dispatch the update back to the main queue.

For more information, refer to the Concurrency Programming Guide.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...