核心数据:如何在添加NSManagedObject后立即更新NSArrayController? [英] Core Data: How to update an NSArrayController immediately after adding an NSManagedObject?

查看:185
本文介绍了核心数据:如何在添加NSManagedObject后立即更新NSArrayController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在核心数据中添加了一个实例。实体由 NSArrayController 表示。我想通过控制器访问新添加的实例。

I am adding an instance in core data. The entity is represented by an NSArrayController. I would like to access the newly added instance through the controller.

添加了一个Skill实例,然后我尝试通过 selectAddedObject 如下:

A "Skill" instance is added and then I try to access it through selectAddedObject as follows:

-(void)addSkill
{
    [self selectAddedObject:[NSEntityDescription insertNewObjectForEntityForName:@"Skill"
                                                          inManagedObjectContext:self.managedObjectContext]];
}

- (void)selectAddedObject:(NSManagedObject *)addedMO
{
    [self.sectionArrayController setSelectedObjects:[NSArray arrayWithObject:addedMO]];
    NSLog(@"Selected: %@", [self.sectionArrayController valueForKey:@"selectedObjects"]);
}

这只适用于我添加

[self.managedObjectContext processPendingChanges];



<但一旦我这样做,文档似乎忘记了它仍然需要保存,我可以退出应用程序,而没有我的添加是自动保存。不想强加给用户!

as the first line of selectAddedObject:. But once I do that, the document seems to forget that it still needs to save, and I could quit the app without my addition being auto-saved. Don't want to force that onto the users!

有什么想法可以立即更新阵列控制器的方式?或者也许以另一种方式添加对象?几个较早的答案(例如将enitiy添加到核心时更新NSTableView

Any ideas on a way to immediately update the array controller in some other way? Or perhaps to add the object in another way? A few earlier answers (e.g. Updating NSTableView when enitiy is added to core data) seem a bit outdated due to changes in OSX.

谢谢!

推荐答案

使用数组控制器添加对象。在配置期间的某个时间点,确保实体被设置( [self.sectionArrayController setEntityName:@Skill] ),然后执行所有工作创建并选择: / p>

Use the array controller to add the object. At some point during configuration, ensure the entity is set ([self.sectionArrayController setEntityName:@"Skill"]) and then do all of your work to create and select:

- (void)createAndSelectNewObject
{
    Skill *addedMO = [self.sectionArrayController newObject];

    if([self.sectionArrayController commitEditing]) {

        [self.sectionArrayController setSelectedObjects:[NSArray arrayWithObject:addedMO]];
        NSLog(@"Selected: %@", [self.sectionArrayController valueForKey:@"selectedObjects"]);
    }
}

您应该在更改选择之前提交任何修改并且只有在编辑已提交或没有任何更改时才更改选择)。

You should commit any edits before changing the selection too (and only change the selection if the edits were committed or there weren't any).

这篇关于核心数据:如何在添加NSManagedObject后立即更新NSArrayController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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