views:

59

answers:

2

Hi,

So I have a UINavigationController which, obviously, contains all my ViewControllers.

I have three.

Root->View2->View3.

So I was wondering is the following possible...

When I'm 'in' View3 (and an instance of Root and View2 are sat on the navigation stack) is it possible for me to call any of View2 or the Root view's methods / send them messages?

If so, how does one go about this? I'll post some sample code if needed.

Thanks,

Jon

+4  A: 

Assuming you're in one of the view controllers, you can do something like this:

UIView* view2    = [self.navigationController.viewControllers objectAtIndex:1];
UIView* rootView = [self.navigationController.viewControllers objectAtIndex:0];

Now you can send them whatever messages you want.

Jason Coco
+2  A: 

NSNotification's work very well for objects you want to have loosely coupled. In a Cocoa/iPhone context, that means no references between them, mostly.

In the controller that may receive the message:

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(doTheThing:) name: @"MessageBetweenControllers" object: nil];

In the controller that needs to send the message:

NSDictionary *dict = [NSDictionary dictionaryWithObject: <some object> forKey: @"key"];
[[NSNotificationCenter defaultCenter] postNotificationName: @"MessageBetweenControllers" object: self userInfo: dict];

The example above is just a template (for example, the NSDictionary bit is optional), but it shows the mechanism. Read the documentation on NSNotification and NSNotificationCenter to get the details.

This is not purely theoretical. It is the primary method I use for inter-object communication in my three published apps and my new one as well. The overhead for the notifications in miniscule.

Two gotchas: Make sure you only ever addObserver once per message -- the NSNotificationCenter does not cull duplicates; if you insert the same observer twice, it will receive the message twice. Also, make sure you do removeObserver in your dealloc method (again, see docs.)

Amagrammer
Also don't forget that messages are received on the same thread that dispatched them and that the dispatching thread will block until the method the received the message returns.
Jason Coco
Good points. I usually use notifications for setting flags and things like forcing tableView reloadData that will return quickly, but you definitely want to be careful what you do on the receiving end of a notification.
Amagrammer
Yeah, that actually bit me once and I didn't expect it ;)
Jason Coco