Domanda

I want to make all reading/writing database operations to background queue and update the current UI view when completed.

There is no problem if user stays in the view while I'm dealing with my database. However, if user left that view before database operations completed, it would crash. The psuedo code is as below:

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 ...];
    });
});
È stato utile?

Soluzione

Try checking if the view is still in the view hierarchy, and also stop the activity indicator from spinning in the viewDidDisappear method as well. You also might need a flag (isNeedingUpdate in the example below) to indicate whether the UI was updated or not, so you can do the appropriate actions if the user goes away before the update is complete and then comes back again.

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];
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top