SHERRIE CRANE
SHERRIE CRANE

Reputation: 133

How to share data between ViewControllers in a tabbed application

I want to share a variable between a few ViewControllers in a tabbed application. I tried using the [NSUserDefaults] to save and load the variables but the application crashes each time. Here is my code in the SecondViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        totalApples = [[NSUserDefaults standardUserDefaults]integerForKey:@"numberOfApples"];
        [self setText:[NSString stringWithFormat:@"%g", totalApples] withExistingAttributesInLabel:self.l1];

    }

It highlights the [super viewDidLoad]; when I click on the tab to open the second view as the cause of the crash.

Upvotes: 1

Views: 652

Answers (2)

Joride
Joride

Reputation: 3763

A tabbarcontroller contains a number of same-level viewControllers (as opposed to a UINavigationController, which contains hierarchical data, so the first viewController passes part of the data on to the next). Those viewControllers need either: - some object to hand them their data - some object they can get the data from.

The second approach requires that those viewControllers have knowledge about the object that can give them their data and is therefore considered rigid design. The first approach implies that you have some higher-level object that can get to the data (or contains it already) and can give it to the viewcontrollers. This is a much more elegant solution as the viewCOntrollers will be more pluggable. The object that you could use here would be a subclass of UITabBarController. This object contains ('knows about') the viewControllers. If this object contains the dat (or can retrieve it), this object would then be able to give it to the viewControllers.

As LudoZik (@LudoZik: I wanted to upvote your answer, but was not allowed due to not having enough rep.). pointed out, create a custom class (or for simplicity an NSDictionary is also OK) that holds the data. This can then be owned by the subclass of the UITabBarController and given to the sub-viewControllers when necessary (e.g. when selected, or maybe already when loaded).

Upvotes: 0

LudoZik
LudoZik

Reputation: 917

Just in case : if you just need to share data between several VCs, NSUserDefaults may not be the best way for your Model. In that case, you may want to consider creating a class where the shared data is located, using the benefits of the singleton design pattern.

Upvotes: 2

Related Questions