I am well into building a Core Data tab-based iPad application. I am passing in my NSManagedObjectContext to my root view using the following in my app delegate class.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.rootViewController.managedObjectContext = self.managedObjectContext;
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
return YES;
}
My question is: how do I set the same managedObjectContext on all my tabs? It would also be good if I could set up some of my service classes in the app delegate and use the same instance across all my tabs. How can this be done?
Thanks in advance!
A "tab" is simply another view controller. As you initiate the VCs for each tab, you can hand them a managed object context in exactly the same way you set rootViewController.managedObjectContext, assuming that they have managedObjectContext properties.
Some people use singleton objects to provide Core Data objects to their classes; what I did in the app I'm currently working on was to declare a protocol, CoreDataSource, with getters for my NSManagedObjectContext, NSManagedObjectModel, and NSPersistentStoreCoordinator, and implemented that protocol on my appDelegate. My view controllers that need to use core data have member variables of type NSObject <CoreDataSource>, and as they create each other they set the property. They're all actually pointing to my appDelegate, but they don't know it, so they're not tightly coupled to an upstream object.
The simplest solution is to add super class for you tab view controllers with a managedObjectContext
attribute and a custom getter method like:
- (NSManagedObjectContext *) managedObjectContext{
if (managedObjectContext !=nil) {
return managedObjectContext;
}
MyAppDelegateClass *appDelegate=(MyAppDelegateClass *)[[UIApplication sharedApplication] delegate];
self.managedObjectContext=appDelegate.managedObjectContext;
return managedObjectContext;
}
If all your tab view controllers inherit this method they will all automatically find the app delegate's managed object context. And you're done.
来源:https://stackoverflow.com/questions/3437033/sharing-nsmanagedobjectcontext-and-other-service-classes-between-iphone-ipad-tab