fogwolf
fogwolf

Reputation: 941

How to share array of data from container/parent view controller and multiple children view controllers

I have a scenario where there is a parent container view controller with a subview taking up most of the screen. This subview is used to swap out 3 different views of the same data (a map, a table and a gallery). There is a segmented control that is used to select which view of the data the user wants to view. I have an array collection of my model type in the parent container view controller and I would like to have these 3 different child view controllers each display this data in their respective views. Is there any clean way to do this without having to duplicate the data 4 times (once in the parent and 3x in the children)? I'm assuming I will have to duplicate the data, because the child should not be able to call up to the parent view controller to access its array. It's also not an appropriate inheritance situation, since the parent is more of a container than the same type of view controller. It's also not a delegate situation, because the children don't need to notify the parent of anything, but the other way around.

Any suggestions greatly appreciated.

Thanks.

Upvotes: 2

Views: 1027

Answers (2)

rocky
rocky

Reputation: 3541

You could put the data in a singleton class and just have each of your child view controllers get the data from the singleton.

Upvotes: 0

didier_v_
didier_v_

Reputation: 174

I would create a class (MyDataController below) to manage the data, and use a shared instance to access it from anywhere in my app.

interface (MyDataController.h)

@interface MyDataController : NSObject {
   NSMutableArray *myData; // this would be the collection that you need to share
}
+ (MyDataController*)sharedDataController;
// ... add functions here to read / write your data
@end

implementation (MyDataController.m)

static MyDataController* sharedDataController; // this will be unique and contain your data

@implementation MyDataController

+ (MyDataController*)sharedDataController
{
    if (!sharedDataController)
        sharedDataController = [[[MyDataController alloc] init] autorelease]; // no autorelease if ARC
    return sharedDataController;
}

// ... implement your functions to read/write data
@end

Finally, to access this static object from anywhere:

MyDataController *dataController = [MyDataController sharedDataController]; // this will create or return the existing controller;

Upvotes: 4

Related Questions