简体   繁体   中英

Shared instance between view controllers in storyboard

I have an app with portrait and landscape orientation. In storyboard I have two view controllers, both using the same subclass "genericVC", and a root view controller which is the initial view controller.

When the app starts, the rootVC will instantiate both controllers and push one of them based on detected orientation. I instantiate them using the method below (rootVC - ViewDidLoad).

    self.landscapeVC = [self.storyboard instantiateViewControllerWithIdentifier:@"iPadLandscapeVC"];
    self.portraitVC = [self.storyboard instantiateViewControllerWithIdentifier:@"iPadPortraitVC"];

What I need is somehow a shared instance for my genericVC class between self.landscapeVC and self.portraitVC, so I don't need to move around the data between them each time I rotate the device.

Please advice me how can be done.

Thanks, Calin

You want one view controller with two views, a portrait and a landscape.

You can add extra nibs or if you are using StoryBoard add an extra view controller in the storyBoard, but give both StoryBoard view controller nibs the same but the viewController class.

It's a bit of pain in StoryBoard if you accidentally switch between portrait and landscape when creating it it mangles things, and you only have access to one at a time. You have to drag one out, and one in to switch which one you are working on

Apple has an example app https://developer.apple.com/library/ios/samplecode/AlternateViews/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008755

Then what you want is a singleton that you can access at anytime during your application life cycle. I won't recommend it as it will stay in memory for the entire app life cycle and it will consume resources that you might not be using at that time.

But as you don't want to share the info using properties between view controllers instances I would suggest you to read this.

https://developer.apple.com/library/ios/documentation/general/conceptual/DevPedia-CocoaCore/Singleton.html

Another possible solution will be to send a dictionary between view controllers using notifications or delegates between them.

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM