views:

496

answers:

3

I have a NSManagedObject object filled with data I want to use in multiple view controllers. Can I make this object into a singleton and use it in multiple view controllers? Or should I use a different approach?

A: 

As an alternative to a singleton, consider making it a property in your application delegate, initialized when the application finishes launching.

In your view controller, set a NSManagedObject reference to this property's value when the view is instantiated.

Alex Reynolds
Okey, thats useful to know, but what do i need to do, when i want to access nsmanagedobject data in multiple controllers?
Ton
If you have a NSManagedObject reference in your controller pointing to the single instance you instantiated in the application delegate, you should be able to access data from it, as you would normally. Take a look at the Cocoa documentation at http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html
Alex Reynolds
You might also want to take a look at the Core Data tutorial, which walks through setting up view controllers: http://developer.apple.com/IPhone/library/documentation/DataManagement/Conceptual/iPhoneCoreData01/Articles/06_Deleting.html#//apple_ref/doc/uid/TP40008305-CH108-SW1
Alex Reynolds
thank you very much!
Ton
+2  A: 

You are already passing around the NSManagedObjectContext. You can use that to fetch the data you want at any time.

I don't know how Core Data would react to you making a singleton instance of it. For one, NSmanagedObject doesn't use the same methods for initialization that NSObject does.

It uses -awakeFromInsert and -awakeFromFetch. So you already have a problem.

See this article from Marcus Zarra (Core Data Guru).

In short, just perform a new fetch to get the data you need, no need to work a singleton in there.

Corey Floyd
What do i need to do when, i have one set of data that, i want to use in multiple controllers. I also need to update the controller views when one controller changes the data of the object.
Ton
Right, if you change the model, post a notification. Then have your view controllers listen for this notification and re-fetch the data if needed.
Corey Floyd
A: 

That depends on why you would want to make it a singleton, if you have trouble passing it to all the entities that need to access the data, using a singleton is not a good solution anyway. It usually introduces more problems rather than solving any.

If you are worried about multiple edits to the same object, Core Data has mechanisms to handle that, see the "Change Management" chapter in the "Core Data Programming Guide"

Harald Scheirich
Actually i would like it to make it a singleton, because i use the same data in that abject in multiple controllers, and in another question on stackoverflow, they answered that i should use a singleton for that kind of situations? instead of passing around refs to the objects.
Ton