0

I will try to make this question as understandable as possible. I am implementing core data in my app, and I need to access the NSManagedObjectContext from around 10,000 different instances of a class (this class extends UIView). The Core Data stores what is displayed on these instances and the class builds it.

Everything that I have found so far uses View Controllers, of which you only have one instance, so you can just alloc init the VC in AppDelegate, set an @property for NSManagedObjectContext and be on your way. This does not work for my program.

What I want to do is have many instances of my CoreDataHelper class (which I will alloc init in the class that I have around 10,000 instances of, which all have a property pointing to the same NSManagedObjectContext. Is this a possible way to do it or will I have to make my program less flexible by moving all of the code to create the 10,000 different objects to the View Controller?

nate.lang
  • 25
  • 1
  • 3

2 Answers2

0

Sure, just put your NSManagedObjectContext in a singleton and all your instances can access the single class.

Community
  • 1
  • 1
Joel
  • 15,654
  • 5
  • 37
  • 60
  • So if my NSManagedObjectContext is a singleton I just reference that singleton when I am initializing my data? – nate.lang Aug 09 '14 at 20:58
  • You can provide a property on your singleton to access the `NSManagedObjectContext` it contains. Then it can be accessed from any class in your application. – Joel Aug 09 '14 at 21:09
0

It does not matter if you get your managed object context from a singleton or from your app delegate (where presumably you the core data stack is set up by default).

To follow the pattern suggested by Apple with view controllers, do the exact same thing with your views: give them a @property of type NSManagedObjectContext and set it during initialization. Seems straight forward enough.

The advantage of the singleton is that you do not even need the property on your view but can call the singleton instead. But why go there? From your comments I understand that you do not really know how a singleton works. You don't need it. Go with the class property solution.

One more caveat: with your setup, you are seriously braking the MVC architecture by giving the views access to your data. Instead, you should indeed have a view controller do this and then populate your views with the retrieved data. I do not think that there is a compelling reason to deviate from this principle.

Mundi
  • 79,884
  • 17
  • 117
  • 140