views:

601

answers:

2

Hi,

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.

A: 

The NSNotification class is a bit heavyweight, but fits the usage you describe. The way it works is that your various NSViewControllers register with an NSNotificationCenter to receive the events they're interested in

Cocoa Touch handles the routing, including providing a singleton-like "default notification center" for you. See Apple's notification guide with more info.

undees
+1  A: 

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
Jed Smith