How to access multiple View controllers from the App Delegate and / or other View controllers?

I suspect this is a very simple answer, or I'm completely wrong. I need to be able to set variables and access fields, etc. In a view controller from an App Delegate or other view controller.

Previously, I could do this from the App Delegate to my first view controller by doing the following in 'doneFinishLaunchingWithOptions':

viewController = (ViewController *) self.window.rootViewController;

After that, I could / could access the methods in the view controller from the App Delegate by doing the usual [viewController someMethod];

If I have multiple view controllers (currently there are 3), how can I access others from other places? By the way, I found SOME explanations, but everyone is talking about nib / xibs in combination with code. I don’t have them, I have a storyboard and code (I am new to the application for developers).

Thanks!

+4
source share
1 answer

In the appDelegate application, you can simply declare properties that will contain links to this viewControllers.

For instance:

in AppDelegate.h

@property (nonatomic, strong) UIViewController *vc1; @property (nonatomic, strong) UIViewController *vc2; 

in AppDelegate.m

 @synthesize vc1,vc2; 

Wherever you create this viewControllers , you can access your appDelegate and set its properties for the correct link. Remember to include AppDelegate.h in this file.

 UIViewController *someVC = [init view controller....]; AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.vc1 = someVC; 

And from now on, you can access this viewController as an appDelegate property.

EDIT: to create a story, it looks safe in - (void)viewDidLoad .

Or even a better approach would be (as Richard said) to do this in - (id)initWithCoder:(NSCoder *)decoder

"When you create an instance of the view controller from the storyboard, iOS initializes the new view controller by calling its initWithCoder: method." from documentation

But note that if you change data from one view controller to another, you may want to save this data in a separate part of the code (the so-called model in the model-view-controller approach). This would be the safest way to "exchange" data between viewControllers.

+5
source

Source: https://habr.com/ru/post/1401238/


All Articles