I use NSNotificationCenter
, which is fantastic for this kind of work. Think of it as an easy way to broadcast messages.
Each ViewController you want to receive the message informs the default NSNotificationCenter that it wants to listen for your message, and when you send it, the delegate in every attached listener is run. For example,
ViewController.m
NSNotificationCenter *note = [NSNotificationCenter defaultCenter];
[note addObserver:self selector:@selector(eventDidFire:) name:@"ILikeTurtlesEvent" object:nil];
/* ... */
- (void) eventDidFire:(NSNotification *)note {
id obj = [note object];
NSLog(@"First one got %@", obj);
}
ViewControllerB.m
NSNotificationCenter *note = [NSNotificationCenter defaultCenter];
[note addObserver:self selector:@selector(awesomeSauce:) name:@"ILikeTurtlesEvent" object:nil];
[note postNotificationName:@"ILikeTurtlesEvent" object:@"StackOverflow"];
/* ... */
- (void) awesomeSauce:(NSNotification *)note {
id obj = [note object];
NSLog(@"Second one got %@", obj);
}
Would produce (in either order depending on which ViewController registers first):
First one got StackOverflow
Second one got StackOverflow