sharing NSManagedObjectContext and other service classes between iphone/ipad tabs

放肆的年华 提交于 2019-12-06 07:57:51

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.

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