在多个选项卡中使用相同的NSManagedObjectContext [英] Working with the same NSManagedObjectContext in multiple tabs

查看:117
本文介绍了在多个选项卡中使用相同的NSManagedObjectContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有不同视图控制器的标签栏控制器,所有这些都使用相同的托管对象上下文,设置如下:

I have a tab bar controller with different view controllers all using the same managed object context, being set up as follows:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

RootViewController *rootVC = [[RootViewController alloc] initWithStyle:UITableViewStyleGrouped];
rootViewController.managedObjectContext = self.managedObjectContext;
UINavigationController *rootNavCon = [[UINavigationController alloc] initWithRootViewController:rootVC];
[rootVC release];

SettingsTableViewController *settingsVC = [[SettingsTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
settingsVC.managedObjectContext = self.managedObjectContext;
UINavigationController *settingsNavCon = [[UINavigationController alloc] initWithRootViewController:settingsVC];
[settingsVC release];

tabBarController = [[UITabBarController alloc] init];
NSArray *controllers = [NSArray arrayWithObjects:rootNavCon, settingsNavCon, nil];
tabBarController.viewControllers = controllers;

[self.window addSubview:tabBarController.view];
[self.window makeKeyAndVisible];

return YES;

}

Recipes示例代码,如果有另一个选项卡名为设置,它提供了一个选项来管理类对象。问题是,如果导航到用户可以选择类别的视图,然后转到设置选项卡并删除,添加或编辑类别,当返回到Recipes选项卡时,更改不会立即反映。因此,选择已删除的类别将引发异常。

The idea is similar to the Recipes sample code if there were another tab called Settings which offered an option to managed the Category objects. The problem is that if you navigate to the view where the user can select the Category, but then go to the settings tab and delete, add, or edit a Category, when returning to the Recipes tab the changes will not be immediately reflected. Thus selecting a deleted Category would raise an exception.

什么是最好的处理方式?我正在考虑设置一个NSNotification,以便在发生重要更改时提醒视图,但不确定是否有更好的方法来执行此操作,例如在出现视图时查询[managedObjectContext hasChanges]。

What is the best way to deal with this? I was thinking about setting up an NSNotification to alert the views whenever an important change had occurred, but wasn't sure if there is a better way to do this, such as querying [managedObjectContext hasChanges] when a view appears. (Although that wouldn't seem to work if the context had already been saved.)

推荐答案

如果您希望更改您的托管对象上下文自动传播到您的界面,并且您正在使用表视图(甚至自定义视图),则可以使用 NSFetchedResultsController 。此类监视更改的上下文并触发其委托方法,只有在必要时才允许重新加载您的视图。

If you want changes to your managed object context to be propagated to your interface automatically and you're using table views (or even custom views), you could be using NSFetchedResultsController. This class watches a context for changes and triggers its delegate methods, allowing you to reload your views only when necessary.

这篇关于在多个选项卡中使用相同的NSManagedObjectContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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