Core Data: How to update an NSArrayController immediately after adding an NSManagedObject?

匆匆过客 提交于 2019-12-13 07:36:08

问题


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.

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"]);
}

This only seems to work if I add

[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!

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.

Thanks!!


回答1:


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).



来源:https://stackoverflow.com/questions/16550891/core-data-how-to-update-an-nsarraycontroller-immediately-after-adding-an-nsmana

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