This document discusses concurrency and threading concepts in iOS development. It provides recipes for moving drawing code to background threads to improve performance, loading data from networks efficiently using Grand Central Dispatch and NSURLSession, and importing data into Core Data in batches to reduce memory usage. It also covers how to make objects thread-safe when accessed concurrently, such as using locks or dispatch queues to synchronize access. The goal is to explain common concurrency patterns and challenges in order to write better multithreaded applications.
16. Moving it to a different thread
[queue addOperationWithBlock:^{
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
// expensive
// drawing
// code
UIImage *i = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// TODO: update the main thread
}];
17. Updating the main thread
[queue addOperationWithBlock:^{
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
// expensive
// drawing
// code
UIImage *i = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = i;
}];
}];
50. You might want to consider using a different
concurrency style, and this time you have two
persistent store coordinators, two almost
completely separate Core Data stacks.
Source: http://asciiwwdc.com/2013/sessions/
211
64. Do it the GCD way
Account* account = [Account new];
Account* other = [Account new];
dispatch_queue_t accountOperations =
dispatch_queue_create("accounting", DISPATCH_QUEUE_SERIAL);
dispatch_async(accountOperations, ^{
[account transfer:200 to:other];
});
dispatch_async will never block.
65.
66. There are two ways of constructing a software
design: One way is to make it so simple that
there are obviously no deficiencies, and the
other way is to make it so complicated that
there are no obvious deficiencies. The first
method is far more difficult.
— Tony Hoare
68. Resources
— Concurrency Programming Guide
— Threading Programming Guide
— NSOperationQueue class reference
— http://www.objc.io/issue-2/
— http://www.opensource.apple.com/source/
objc4/objc4-551.1/runtime/objc-sync.mm
— http://googlemac.blogspot.de/2006/10/
synchronized-swimming.html
— WWDC12 #211: Concurrent User Interfaces on
iOS
69. Icons are from the Noun Project:
— Coffee Maker by Maureen Placente
— Coffee by Julia Soderberg
— Railroad Crossing by Edward Boatman
— Database by Stefan Parnarov
— Drawing by Daniel Shannon
— Hammer by Alex AS
— Lock by P.J. Onori
— Photoshop by Joe Harrison
— Register by Wilson Joseph