1

我想使所有讀取/寫入數據庫操作都能夠到後臺隊列並在完成時更新當前UI視圖。用戶在執行dispatch_get_main_queue()之前留下當前視圖

如果用戶在處理數據庫時停留在視圖中,則沒有問題。但是,如果用戶在數據庫操作完成之前離開該視圖,則會崩潰。所述僞代碼如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ 

/* save data to database, needs some time */ 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     // back to main queue, update UI if possible 
     // here may cause crash 
     [self.indicator stopAnimating]; 
     [self.imageView ...]; 
    }); 
}); 
+0

什麼是崩潰? –

+0

整個屏幕凍結,但指示器微調器保持旋轉。 – benck

+0

這不是一個崩潰。你提到了崩潰。 –

回答

1

嘗試檢查如果視圖仍然在視圖層次,並且還從在viewDidDisappear方法紡絲以及停止活動的指標。您還可能需要一個標誌(下面示例中的isNeedingUpdate)來指示UI是否已更新,因此如果用戶在更新完成之前消失並再次返回,您可以執行相應的操作。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ 
    if (self.view.window) { // will be nil if the view is not in the window hierarchy 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self.indicator stopAnimating]; 
      [self.imageView ...]; 
      self.isNeedingUpdate = NO; 
     }); 
    }else{ 
     self.isNeedingUpdate = YES; 
}); 


-(void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
    if (isNeedingUpdate) { 
     // do whatever you need here to update the view if the use had gone away before the update was complete. 
    } 
} 


-(void)viewDidDisappear:(BOOL)animated { 
    [super viewDidDisappear:animated]; 
    [self.indicator stopAnimating]; 
} 
相關問題