开发者

How to access one UIViewControllers properties from another UIViewController?

I have one single MainViewController which has of course it's one main UIView. I have this main view comprised of many different subviews.

Some of these subviews have their very own ViewController.

Lets say the MAIN view (whose delegate is primarily MainViewController) has a container which loads another UIView that uses a separate UIViewController- SecondaryViewController as the delegate for most it's actions.

This container view is of course loaded in MainViewController via

MyContainerViewController *myContainerController = 
         [[MyContainerViewController alloc] ...]; 
[self addSubView: myContainerController.view];

the controller for myContainerController.view th开发者_JAVA技巧ough is MyContainerViewController. How inside this controller do I access MainViewController properties? Specifically I need to access MainViewController's - self.navigationController property to push a new ViewController? :)

Does this make any sense? I assume there's going to be casting of some sort involved since it seems I need to somehow retain a reference to MainViewController inside SecondaryViewController?


It doesn't make sense to push a new ViewController from the SecondaryViewController in the MainViewController. This screws up the design of the code. A child object will access its parents method to call a method. By other words: bad code. Make a delegate call from the SecondaryViewController to the MainViewController that it state has changed. Then the MainViewController can decide to do with the call and the SecondaryViewController will not know anything about the implementation of the MainViewController.

So: Make a protocol in SecondaryViewController. Let the MainViewController be SecondaryViewController's delegate. Implement the delegate method in MainViewController which pushes the new ViewController.


Expose the desired sub-view controllers as properties of the view controller that contains them.

Expose your root view controller(s) as properties of your app delegate, and synthesize them also.

When you want to access a different UIViewController, first obtain a reference to your appDelegate:

MyAppDelegate* myAppDelegate = [[UIApplication sharedApplication] delegate];

Then just use your chain of properties to get access to your desired view controller.

SubSubViewController* ssvc = myAppDelegate.rootViewController.subViewController.subSubViewController;

Some folks frown upon the use of the sharedApplication class method to obtain the reference to a delegate, but I've used it in multiple apps and not suffered for it (yet). The alternative is to pipe your appDelegate through your hierarchy of viewControllers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜