永远不要使主线程承担过多。因为UIKit在主线程上做所有工作,渲染,管理触摸反应,回应输入等都需要在它上面完成。
一直使用主线程的风险就是如果你的代码真的block了主线程,你的app会失去反应。这。。。正是在App Store中拿到一颗星的捷径 :]
大部分阻碍主进程的情形是你的app在做一些牵涉到读写外部资源的I/O操作,比如存储或者网络。
你可以使用`NSURLConnection`异步地做网络操作:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue*)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
或者使用像AFNetworking这样的框架来异步地做这些操作。
如果你需要做其它类型的需要耗费巨大资源的操作(比如时间敏感的计算或者存储读写)那就用 Grand Central Dispatch,或者 NSOperation 和 NSOperationQueues.
下面代码是使用GCD的模板
1 2 3 4 5 6 7 8 |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // switch to a background thread and perform your expensive operation
dispatch_async(dispatch_get_main_queue(), ^{ // switch back to the main thread to update your UI
}); });
|
发现代码中有一个嵌套的`dispatch_async`吗?这是因为任何UIKit相关的代码需要在主线程上进行。
如果你对 NSOperation 或者GCD 的细节感兴趣的话,看看Ray Wenderlich的Multithreading and Grand Central Dispatch on iOS forBeginners,还有 Soheil Azarpour 的How To Use NSOperations and NSOperationQueues教程。