I was wondering what is the best practice for an application flow in iPhone development.
How do you pass messages between ViewControllers?
Do you use singletons? pass it between views or do you have a main controller for the application that manage the flow?
Thanks.
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,
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With