views:

856

answers:

2

Hi, 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?

Thanks, Michael

+1  A: 

Note the selector name: "insert New Object:inContext".

As amrox says, it depends on how your model (i.e. Core Data) and your controller are connected. It's hard for me to say without knowing more about your code, especially since I'm usually more on the iPhone side of things (which doesn't have bindings), but basically you need to be saying [[yourDataArray objectAtIndex:[table selectedRow]] setValue:@"whatever" forKey:@"whatever"]

refulgentis
+2  A: 

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.

Abizern
hmm, I tried that, but the figure in the table won't update,I've basically put in that code, changed it to fit my program, then reloaded the table.
Michael
Works for me. I've added a link to an example project that you can download to see what you need to do.
Abizern
Thank you SO much for that sample code, it made me finally see what I was doing wrong! Thanks for all your help!
Michael