Carelinkz
Carelinkz

Reputation: 936

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

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

Upvotes: 0

Views: 1057

Answers (1)

Wain
Wain

Reputation: 119031

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

Upvotes: 1

Related Questions