Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone sdk pass messages between view controllers

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.

like image 565
lnetanel Avatar asked Dec 14 '22 01:12

lnetanel


1 Answers

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
like image 117
Jed Smith Avatar answered Dec 30 '22 01:12

Jed Smith