在iphone / ipad标签之间共享NSManagedObjectContext和其他服务类 [英] sharing NSManagedObjectContext and other service classes between iphone/ipad tabs

查看:198
本文介绍了在iphone / ipad标签之间共享NSManagedObjectContext和其他服务类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个基于Core Data选项卡的iPad应用程序。我在我的应用程序代理类中使用以下代码将我的NSManagedObjectContext传递到我的根视图。

   - (BOOL) UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.rootViewController.managedObjectContext = self.managedObjectContext;
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];

return YES;
}



我的问题是:如何在所有选项卡上设置相同的managedObjectContext?它也将是好的,如果我可以在应用程序委托中设置一些服务类,并在所有我的选项卡使用相同的实例。

解决方案



< 标签只是另一个视图控制器。当您为每个选项卡启动VC时,您可以使用与设置rootViewController.managedObjectContext完全相同的方式处理受管对象上下文,假设它们具有managedObjectContext属性。



有些人使用单例对象来为他们的类提供Core Data对象;我在我目前工作的应用程序是做宣布一个协议,CoreDataSource,与我的NSManagedObjectContext,NSManagedObjectModel和NSPersistentStoreCoordinator的getters,并实现我的appDelegate的协议。我需要使用核心数据的视图控制器具有类型NSObject< CoreDataSource>的成员变量,并且当他们创建彼此时,他们设置属性。他们实际上指向我的appDelegate,但他们不知道它,所以他们没有紧密耦合到上游对象。


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.

这篇关于在iphone / ipad标签之间共享NSManagedObjectContext和其他服务类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆