How to transfer information between two UIViewControllers in a UITabBarController

There are two UIViewControllers in my iPhone application; both are built into the UITabBarController. However, when the TabBarController and VC switch are connected, the VC on the screen loads the data into NSUserDefaults, and then the transition VC retrieves this data from NSUserDefaults.

What I'm doing now is load the data into viewWillDisappear from the first VC, and then extract it into viewWillAppear of the second VC. the problem is that viewWillAppear from VC, which is about to appear on the screen, is called before the ViewWillDash view from the "old" VC , so it tries to get data that has not yet been loaded.

What can I use, so the β€œold VC” is the first one to know when it is about to go to the screen so that it can load data before the new one retrieves this data?

* I also tried to configure UITabBArControllerDelegate so that the old VC would get - tabBarController: didSelectViewController: but this is also called too late.

+1
source share
3 answers

If you are not going to pass a lot of information, you can use the default variables as one of the many options available. It may not be the best, but it will work.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:Variable forKey:@"variable"]; [defaults synchronize]; 

To set variables

and

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSString *fetchVariable = [defaults objectForKey:@"variable"]; 

to get it in another VC.

+4
source

What can I use, so the β€œold VC” is the first one to know when it is about to go to the screen so that it can load data before the new one retrieves this data?

You can try using the method – tabBarController:didSelectViewController: UITabBarControllerDelegate to save data to NSUserDefaults ; this must be called before viewWillAppear in any controller.

If you want to keep your current approach, try using viewDidAppear: instead of viewWillAppear: in the second view controller. This should work correctly if you are not extracting a lot of data from NSUserDefaults (as it should be, I think), and if your second controller user interface does not introduce a delay in displaying the data.

Another approach you have is to make the first controller update its data in NSUserDefaults every time it changes.

0
source

Recording and reading sounds are like unnecessary overhead. If you don’t need to write this at all, of course.

I would make the previous UIViewController pass all the data wrapped in the object to the UITabBarController , which would then pass it to the new UIViewController . If this is the template for all (or most) of your tabs, create a new protocol and let your UIViewController implement this. Then your UITabBarController will be able to determine which controllers need it by simply checking if the controller matches your protocol.

0
source

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


All Articles