views:

406

answers:

3

Hi, I'm currently developping my first iPhone application and I would like to know what is the best way to share an object which is gonna be used in every controller.

I was thinking of referencing the controller containing the needed data in other controllers and access this data thanks to properties, is that a good idea or is there a better way to do it?

Or can we declare any global variable (not const) accessible anywhere in the application?

Thank you

A: 

If you really need it to be global, you can put it in the AppDelegate or create a data management object. But I think it's frowned upon to do it like that.

John
+3  A: 

It's not clear from your question what kind of data you are dealing with, but one approach I have used in iphone applications is a singleton object that contains application state and state management functions.

There is a good discussion of the use of singletons versus app delegates for this type of data found at Cocoa With Love and I agree with what he has to say here.

For instance the application in this case had a user account tied to a web application so on load the application would initialize the singleton object and when the user signed in it would keep a reference to the user object in the singleton so that user info could be referenced for api calls.

This approach has worked fairly well for my purposes you can see how to create a singleton class in Objective-C here, and also in the apple docs here there are several ways to do it which provide the same functional result.

Once you have defined your singleton class you can initialize it in applicationDidFinishLaunching or in the viewDidLoad of your main controller and init the globally accessible data you are needing to manage. I highly recommend you read the Cocoa With Love article I linked above for some consideration of managing this whole process.

Hope that helps.

If you're stuck I can post some example code, but the singleton class examples available are pretty straightforward to work with.

paulthenerd
A: 

The singleton looks good for what I want to do, I need to have a research object containing several filters that can be changed in my application.

thank you guys

Mathieu