sizeWithFont 不是线程安全。
生活随笔
收集整理的這篇文章主要介紹了
sizeWithFont 不是线程安全。
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?在ios開發(fā)中經(jīng)常使用用sizeWithFont 方法來計(jì)算UILabel 的frame, 例如動(dòng)態(tài)計(jì)算UITableViewCell 的高度,在主線程處理沒有問題,但是在子線程用此方法來計(jì)算就會(huì)出現(xiàn)Crash,因?yàn)?UIStringDrawing 中的方法不是線程安全的。以下代碼在ios6 模擬器中測試過:
dispatch_queue_t queue = dispatch_queue_create("com.queue", NULL);for (int i = 0; i < 10000; i++) {dispatch_async(queue, ^{NSString *string = @"My string";CGSize size = [string sizeWithFont:[UIFont boldSystemFontOfSize:13]];}); }for (int i = 0; i < 10000; i++) {NSString *string = @"My string";CGSize size = [string sizeWithFont:[UIFont boldSystemFontOfSize:13]]; }dispatch_release(queue);錯(cuò)誤代碼:
WebCore`WebCore::FontFallbackList::invalidate(WTF::PassRefPtr<WebCore::FontSelector>): 。。。 0x2b635d8: jne 0x2b635f1 ; WebCore::FontFallbackList::invalidate(WTF::PassRefPtr<WebCore::FontSelector>) + 65 0x2b635da: calll 0x2b5b740 ; WebCore::fontCache() 。。。 0x2b635ec: calll 0x2b5c210 ; WebCore::FontCache::releaseFontData(WebCore::SimpleFontData const*) 0x2b635f1: incl %ebx 。。。0x2b63620: calll 0x364281a ; symbol stub for: WTF::fastFree(void*) 0x2b63625: movl $0, 4(%ebx) 。。。0x2b63674: je 0x2b63696 ; WebCore::FontFallbackList::invalidate(WTF::PassRefPtr<WebCore::FontSelector>) + 230 。。。 0x2b6367f: je 0x2b63686 ; WebCore::FontFallbackList::invalidate(WTF::PassRefPtr<WebCore::FontSelector>) + 214 0x2b63681: decl %ecx 0x2b63682: movl %ecx, (%eax) 0x2b63684: jmp 0x2b63693 ; WebCore::FontFallbackList::invalidate(WTF::PassRefPtr<WebCore::FontSelector>) + 227 0x2b63686: addl $-4, %eax 0x2b63689: je 0x2b63693 ; WebCore::FontFallbackList::invalidate(WTF::PassRefPtr<WebCore::FontSelector>) + 227 0x2b6368b: movl (%eax), %ecx 。。。 0x2b63698: testl %ecx, %ecx 0x2b6369a: je 0x2b636a4 ; WebCore::FontFallbackList::invalidate(WTF::PassRefPtr<WebCore::FontSelector>) + 244 0x2b6369c: movl (%ecx), %eax 。。。 0x2b636a7: calll 0x2b5b740 ; WebCore::fontCache() 0x2b636ac: movl %eax, (%esp) 0x2b636af: calll 0x2b5cce0 ; WebCore::FontCache::generation() 。。。 0x2b636bf: ret所以,建議使用UIStringDrawing放在主線程中使用。
stackoverflow上也有其他計(jì)算方法,本人沒試過。
參考:
http://stackoverflow.com/questions/12744558/uistringdrawing-methods-dont-seem-to-be-thread-safe-in-ios-6
轉(zhuǎn)載于:https://www.cnblogs.com/zeejun/p/3261117.html
總結(jié)
以上是生活随笔為你收集整理的sizeWithFont 不是线程安全。的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 8月14小练
- 下一篇: 浮动5-常用列表显示(案例)