tags:

views:

1027

answers:

2

I have an app that allows the user to view, manipulate and manage a collection of Schedule objects. Different parts of the app need access to this data. I've experimented with making the collection a singleton, but I didn't find that very clean.

I recently changed to storing the global data in the AppDelegate class and using:

MyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.myGlobalData doSomething];

Which eliminates the need for my global data to be a singleton, but is really just taking advantage of the UIApplication singleton.

There really isn't just one primary view controller where it makes sense to store it in my case. So I was wondering what different strategies people use to address this.

+3  A: 

Many people store everything in the AppDelegate and access the data through [[UIApplication sharedApplication] delegate].

If the data are supposed to be persisted, you could also use the NSUserDefaults singleton.

If the data are big, maybe you need SQLite.

This is for "global" data as you asked.

If your view controllers are organized in tree, a better way would be passing the required data from parent UIViewController to child UIViewController.

nst
+6  A: 

If you've got a central data model that needs to be accessible to multiple controllers, there's nothing wrong with using a singleton to manage the data-- a "sharedManager" is exactly what the scenario demands. This is essentially what Apple does with their address book API for manipulating contacts. They use a C-style API but it involves getting a reference to the shared address book database and then using that in future calls.

Using the app delegate works too, but as you note it's really the same thing. You're designating the app delegate singleton as the owner of the data model, which is OK too.

NSUserDefaults can be abused in this way but that's really not its purpose. Aside from being kind of ugly, it also puts restrictions on the type of data you can store. Your own model can store whatever data you like, but NSUserDefaults is not quite so flexible.

Using SQLite or a property list or whatever to store the data to a file is really orthogonal to the question of how to manage it. From your description a singleton approach sounds reasonable, and that singleton can write to files in whatever way makes sense for the data you're working with.

Tom Harrington