سؤال

I want to do the following:

1. display loader
2. download database update and reload data
3. hide loader

My idea is to send notifications at the begining and at the end of Database's update method to the main view controller, so that the view controller displays and hides the loader.

I am worried about the control flow. Do I have any guarantee that the view controller will receive the notification and display the loader before the Database's update method proceeds?

هل كانت مفيدة؟

المحلول

The notifications are queued in the system, so there's no guarantee it's going to be instantly. Anyway, they are usually quite fast, for sure faster than the work on the database.

If you want to be 100% sure, just set a flag somewhere and when you receive the notification, check that the databases is reloaded.

Anyway, I'm just thinking that even if the notification is received after the reload of the database, because the notification are queued, the hide loader notification will come right after the first one, so there would be nothing to worry about.

نصائح أخرى

Usually you would want the viewcontroller to kickoff the updating, so as long as you make sure you set the listener before that (the kickoff of the updating), and after your viewcontroller has loaded completely you should be fine. (i.e. start the updating in viewDidAppear)

You could implement it like the following:

- (IBAction)updateDatabase:(id)sender {
    __block MyController* blockSelf = self;
    __weak MyController* weakSelf = self;
    [self startBusyIndicator];
    [self asyncDownloadDatabase:^(id result, NSError*error) {
        if (error == nil) {
            [blockSelf.database updateWithData:result];
        }
        blockSelf = nil;
        MyController* strongSelf = weakSelf;
        if (strongSelf) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [strongSelf reloadData];
                [strongSelf stopBusyIndicator];
            });
        }
    }];
}

Using blockSelf guarantees that the controller is kept alive until after asyncDownloadDatabase is finished and the database is updated. It is assumed that the update process can be executed on any thread.

weakSelf will become zero only and immediately until after blockSelf is set to nil, iff that was the last reference to the controller - e.g. the user has switched away to another view. In this case, no views will be updated - they are already deallocated. Otherwise, if the controller still exist, the views will be updated.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top