wkv5cw
Last Updated: February 25, 2016
·
559
· widescape

Update UILabel in SubViewController from MainViewController

Even though you are able to let your MainViewController directly call a method such as updateLabel defined in SubViewController, the view of the SubViewController will not be updated then. Even if you call setNeedsDisplay or force to be on the main thread. It all. won't. help.

The only thing that helped me was implementing a NSNotificationCenter postNotification called by MainViewController and observed by SubViewController.

Example:

// MainViewController.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  …
  [[NSNotificationCenter defaultCenter] postNotificationName:@"profileLoaded" object:userName];
}

// SubViewController.m
- (void)viewDidLoad {
  …
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setUserName:) name:@"profileLoaded" object:nil];
}

- (void) setUserName:(NSNotification *)note {
  [_userNameLabel setText: note.object];
}

- (void) dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

An alternative is using delegates. (But I didn't want to go that road.)