views:

2863

answers:

3

I've looked through all the class documentation for Core Data and I can't find away to programmatically update values in a core data entity. For example, I have a structure similar to this:

 id  | title
============
  1  | Foo  
  2  | Bar  
  3  | FooFoo

Say that I want to update Bar to BarBar, I can't find any way to do this in any of the documentation.

+2  A: 

The Apple documentation on using managed objects in Core Data likely has your answer. In short, though, you should be able to do something like this:

NSError *saveError;
[bookTwo setTitle:@"BarBar"];
if (![managedObjectContext save:&saveError]) {
    NSLog(@"Saving changes to book book two failed: %@", saveError);
} else {
    // The changes to bookTwo have been persisted.
}

(Note: bookTwo must be a managed object that is associated with managedObjectContext for this example to work.)

Evan DiBiase
+3  A: 

Sounds like you're thinking in terms of an underlying relational database. Core Data's API is built around model objects, not relational databases.

An entity is a Cocoa object—an instance of NSManagedObject or some subclass of that. The entity's attributes are properties of the object. You use key-value coding or, if you implement a subclass, dot syntax or accessor methods to set those properties.

Evan DiBiase's answer shows one correct way to set the property—specifically, an accessor message. Here's dot syntax:

bookTwo.title = @"BarBar";

And KVC (which you can use with plain old NSManagedObject):

[bookTwo setValue:@"BarBar" forKey:@"title"];
Peter Hosey
+4  A: 

If I'm understanding your question correctly, I think that all you need to keep in mind is managed objects are really no different than any other Cocoa class. Attributes have accessors and mutators you can use in code, through key value coding or through bindings, only in this case they're generated by Core Data. The only trick is you need to manually declare the generated accessors in your class file (if you have one) for your entity if you want to avoid having to use setValue:ForKey:. The documentation describes this in more detail, but the short answer is that you can select your attributes in the data model designer, and choose Copy Obj-C 2.0 Method Declarations from the Design menu.

Marc Charbonneau