How to pass information between two UIViewControllers in a in a UITabBarController

余生颓废 提交于 2019-12-06 16:32:37

If you're not going to be transmitting a lot of information, you can make use of default variables as one of the many options available. It might not be the best, but it'll work.

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

To set the variables

and

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

to retrieve it in the other VC.

Writing and reading back sounds like an unnecessary overhead. Unless you need to write it anyway, of course.

I'd make the previous UIViewController pass all data wrapped in an object to the UITabBarController, which would then pass it to the new UIViewController. If this is a pattern for all (or most of) your tabs, create a new protocol and let your UIViewControllers implement that. Your UITabBarController would then be able to figure out which controllers need it by simply checking if the controller conforms to your protocol.

What can I use so the "old VC" is the first one to know when it is about to go offscreen so it can upload the data before the new one fetches that data?

You can try using the – tabBarController:didSelectViewController: UITabBarControllerDelegate method to save the data in NSUserDefaults; this should be certainly 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 properly if you are not fetching a lot of data from NSUserDefaults (as it should be the case, I guess) and if your second view controller UI does no introduce a delay in showing the data.

Another approach you have is making the first controller update its data in NSUserDefaults each time it changes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!