Common multithreading mistakes beginners make on iPhone

后端 未结 2 865
栀梦
栀梦 2020-12-13 01:10

I just introduced multithreading into my app JUST to get a silly UIActivityIndicatorView to work. Well, the activity indicator works, alright -- but now my app crashes somet

2条回答
  •  Happy的楠姐
    2020-12-13 01:52

    This question has some good resources on Cocoa multithreading: "Where can I find a good tutorial on iPhone/Objective c multithreading?"

    I also highly recommend reading the new Concurrency Programming Guide (however, ignore the blocks and dispatch queues, as Grand Central Dispatch is not yet available on iPhone OS iOS 4.0 just added blocks and GCD), because it makes a strong case for using structures like NSOperation and NSOperationQueue as an alternative to manually created threads. For information on manually created threads, refer to the Threading Programming Guide.

    As RC mentions, the single biggest source of crashes with multithreaded Cocoa applications is simultaneous access to a shared resource. The @synchronized directive is not the fastest, as pointed out by Colin Wheeler, so you might want to use NSLock to protect access to your shared resources. However, locking of any sort can be expensive, which is why I've been migrating my applications over to using single-wide NSOperationQueues for access to these resources. The performance improvements have been significant.

    Another problem area with Cocoa and multithreading comes from user interface updates. All UI updates in Cocoa must be done on the main thread, or instability can result. If you have a background thread performing a calculation, make sure to wrap whatever method updates the UI in a -performSelectorOnMainThread:withObject:waitUntilDone: method call.

提交回复
热议问题