objective-c – 在後臺執行緒上建立UIView可以嗎?
我知道UIView不是執行緒安全的,所以我不能在後臺執行緒上新增檢視,解決這個問題是否可以在後臺執行緒上建立一個UIView,然後將其新增到主執行緒?
注意:在主執行緒上不這樣做的原因是因為我的實際程式碼更復雜,因此需要一段時間來建立所有的檢視並填充值.當我這樣做時,我不希望UI變得不響應,所以我試圖解決這個問題.
例如..
-(void)addLabel//called on background thread { UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0,0,40,100)]; [label setText:@"example"] [self.view performSelector:@selector(addSubview:) onThread:[NSThread mainThread] withObject:example waitUntilDone:YES]; }
提前致謝.
:
Threading Considerations Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself but all other manipulations should occur on the main thread.
對initWithFrame的呼叫顯然不是執行緒安全的.對setText的呼叫可能不是執行緒安全的,落在“操縱”子句下.這些肯定不會是執行緒安全的.
做你的工作,找出背景線上的資料.然後在主執行緒上建立您的檢視.如果有大量的檢視,您可以嘗試使用幾個dispatch_async()呼叫分割到主佇列上.這可能讓UI保持響應;我沒有廣泛地嘗試過.
您也可以考慮在可能的情況下從UIView切換到CALayer.大多數CALayer工作可以在後臺執行緒上完成.如果你有很多觀點,那可能是低效的.如果只是計算檢視的資料需要很長時間,這表明您沒有正確分離模型和檢視資訊. Model類應該獨立於建立檢視來計算所需的所有內容.
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/11122957/is-it-ok-to-create-a-uiview-on-a-background-thread