Calculating string sizes on iPhone on a background thread
I've got some somewhat hefty string size c开发者_StackOverflow社区alculations happening in my app (each one takes close to 500ms, and happens when the user scrolls to a new "page" in my app (like the Weather app). The delay only happens once per page, as the calculation only needs to be run once (and can even be cached for subsequent launches with the same data).
Anyway, I still like to not block the UI for this type of work, as to me it screams using threads, but I know UIKit is not meant to be used from other threads. (I know NSString is not part of UIKit, but the string sizing methods are part of the UIKitAdditions...)
So how should I go about doing this? What's the best way to not block the UI and do so safely?
I always used -sizeWithFont
and friends on background threads to calculate cell heights etc. It worked just fine. However, since iOS 6.0 it causes intermittent crashes. Hope these will be fixed because it's an essential performance optimization to calculate UI layouts in the background.
Consider using NSOperation
/NSOperationQueue
. There's a tutorial on Cocoa Is My Girlfriend, and Apple has a guide.
I may be wrong, but I believe the prohibation of using UIKit in other threads is related to the general way that GUI's work (being single threaded) and normally is only applied to situations where the GUI itself is affected.
The sizeWithFont:
method does not actually affect the GUI in anyway so I don't think there would be a problem with calling this in another thread.
Maybe an iPhone person with more experience in how this method works behind the scenes can confirm my thinking or set me straight.
精彩评论