JonB
JonB

Reputation: 4662

Accessing Other views on Navigation Stack

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

Upvotes: 0

Views: 115

Answers (2)

Amagrammer
Amagrammer

Reputation: 6373

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.)

Upvotes: 2

Jason Coco
Jason Coco

Reputation: 78353

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.

Upvotes: 4

Related Questions