IPhone sdk sends messages between view controllers

I was wondering what is the best practice for stream apps on iPhone.
How do you pass messages between ViewControllers? Do you use single player games? pass it between views or do you have a main controller for the application controlling the flow?

Thanks.

+4
source share
2 answers

I use NSNotificationCenter , which is fantastic for this kind of work. Think of it as an easy way to send messages.

Each ViewController that you want to receive a message tells NSNotificationCenter by default that it wants to listen to your message, and when you send it, a delegate is executed in each connected listening device. 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); } 

It will be done (in any order, depending on which ViewController register is registered first):

 First one got StackOverflow Second one got StackOverflow 
+13
source

The NSNotification class is a bit heavy, but matches the description you describe. The way it works is that your various NSViewController are registered using NSNotificationCenter to get events of interest to them.

Cocoa Touch handles routing, including providing you with a one-tone "default notification center." See the Apple notification guide for details.

0
source

All Articles