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?
views:
496answers:
3As 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.
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.
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"