The Concurrency Programming Guide by Apple is a nice reading. Concurrent programming is not something you might want to pick up by copying some sample code from the web and hacking until you are happy. It’s good to know the options and principles to save yourself from trouble.
Revisiting the answer after some time, nowadays you almost can’t go wrong using Grand Central Dispatch. Running a task in background looks like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self doSomeLongTask]; // 1
dispatch_async(dispatch_get_main_queue(), ^{
[self longTaskDidFinish]; // 2
});
});
The long task (1) will run on some background thread and there’s no catch that I am aware of, ie. there’s already an autorelease pool in that thread, you don’t have to care about run loops etc. After the task finishes the code calls -longTaskDidFinish
on the main thread (2), so that you can update UI or whatever else. This is an often used idiom.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…