sharing NSManagedObjectContext and other service classes between iphone/ipad tabs

旧巷老猫 提交于 2019-12-22 18:19:43

问题


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!


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!