Search code examples
iosobjective-ckey-value-observing

iOS: Key-Value Observing does not dismiss modal view


I have the following key value observer method in a modal view:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
  if ([keyPath isEqualToString:@"uploadComplete"]) {
    NSLog(@"UploadVC hears upload complete");
    [self dismissViewControllerAnimated:YES completion:nil];
  }
}

I use this to watch a photo object and know when it is finished uploading. When I run this it behaves as expected, and the console logs "UploadVC hears upload complete" - but then the following line is not executed -- the modal does not get dismissed.

There are no errors or anything else, the view just sits there and the modal is never dismissed. What's going on here?


Solution

  • That may happen when you receive KVO notification on background thread and so attempts to update UI may result in any unexpected behaviour (UI not changed, changed after some delay, app crash etc etc). Make sure you call all updating UI code on main thread:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
      if ([keyPath isEqualToString:@"uploadComplete"]) {
         NSLog(@"UploadVC hears upload complete");
         dispatch_async(dispatch_get_main_queue(), ^{
             [self dismissViewControllerAnimated:YES completion:nil];
         });
    
      }
    }