Suppose I create a new project with core data. A project with a root view controller.
By default, Apple adds a self.managedObjectContext reference to this main viewController.
Now I add other classes to my project.
At some point I will have to read the objects from the core data entities and I will have to access that managedObjectContext. How do you guys obtain that context from other classes?
I know I can import the rootViewController.h on the class I want to access the context, but I am trying to do that without importing the header on multiple classes, because I want to make the classes as much independent of each other as possible and because I think this is not a good solution as it will create a mess of cross references between classes. I may be wrong.
I now I can use:
managedObjectContext = [(MyAppDelegateName *)[[UIApplication sharedApplication] delegate] managedObjectContext];
but then I will have to import MyAppDelegateName.h and the problem is the same.
Is there a better way to do that? How do you solve that?
t开发者_StackOverflow中文版hanks.
Reduce dependency on CoreData by wrapping either with Repository design pattern, or with just a high level Model that handles all Core Data interactions for you. Then either have the model as a statically available class, singleton it (not recommended), or pass it through your ViewControllers.
Edit:
Repository Pattern - define specific repositories for each of your data objects. For example, if you have Suppliers and Products, you would have 2 repository classes, and each Repository conforms to a set interface. As a illustrative example:
@protocol Repository{
-(id)GetByKey:(NSInteger *)key;
-(id)GetAll;
-(id)RemoveByKey:(NSInteger *)key;
-(id)RemoveAll;
}
@interface SupplierRepository:NSObject <Repository>
@end
@interface ProductRepository:NSObject <Repository>
@end
Your core data entities will also need to conform to some conventions, such as a surrogate key. I've never done this, so someone else may be able to better explain. Depending on your tolerance rating, you may decide to just instantiate repositories in your ViewControllers, or you may decide to just put it in a single Model instance anyway.
精彩评论