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]; 
} 
相关问题