views:

115

answers:

2

I am building a simple document-based application in cocoa and I'm having problems to link common data between my document instances.

I'd like to have some sort of AppController and have all my documents to access the same instance of this class.

Instancing the object in document.xib will create different instances for each document. And Instancing the object in MainMenu makes the object inaccessible.

How can I achieve that?

+1  A: 

A typical approach is to create a singleton instance of an AppController object. You may as well create an AppController instance and hold it in your AppDelegate. You can then later access it from everywhere in your code by calling

[[NSApp delegate] myAppController]

or on the iPhone:

[[UIApplication sharedApplication].delegate myAppController]

Further reading on the brilliant cocoawithlove blog http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

stigi
A: 

Assuming that you have a good reason for separate documents to share data (as opposed to, say, putting it in a Preferences window or something), you should probably make the SharedDataController (“AppController” is very broad) a singleton. I have a blog post about the correct way to make one.

Peter Hosey