Cocoa – NSManagedObject setValue problem (Core Data)

cocoacore-datasetvalue

I wish to edit an existing record in core data. At the moment, I have this code, but it creates a new record (and inserts the correct data into the correct column):

NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];
NSManagedObject *instrument  = nil;



instrument = [NSEntityDescription insertNewObjectForEntityForName: @"Instrument"
                  inManagedObjectContext: context];

[instrument setValue:[NSNumber numberWithInt:quantityInStockInstruments] 
    forKey: @"quantity"];

The result will look like this:

Instrument | Value | Quantity

Violin     | £25   | 9

           |       | 8 <<< This is the new record that is created, instead of setting the
                           quantity of violin from '9' to '8'

I want the program to edit the quantity column of the currently highlighted row, (which in this case is the 'violin' row. How would I do this?

Best Solution

As refulgentis said, the clue is in the name of the selector. You’re adding a new object.

A better way to do it, rather than using the table, is by using the selectedObjects of your NSArrayController. As an example (this is long winded for clarity and I’ve written it off the top of my head):

// Get the selected objects from the NSArrayController.
// There may be more than one object selected, so this needs to be accounted for.
NSArray *selectedObjectsArray = [yourArrayController selectedObjects];

// Get the first object in the array, this is the one that will have it's values changed.
id firstSelectedObject = [selectedObjectsArray objectAtIndex:0];

// Change a value in a KVC compliant way
[firstSelectedObject setValue:newValue forKey:@"keyValueToChange"];

Edited to add after the comment

Have you got an outlet to the array controller and connected it correctly in Interface Builder?

Anyway, the code works for me. Here’s an example project showing it working.

Related Question