Programmatically Update an attribute in Core Data Programmatically Update an attribute in Core Data objective-c objective-c

Programmatically Update an attribute in Core Data


In Core Data, an object is an object is an object - the database isn't a thing you throw commands at.

To update something that is persisted, you recreate it as an object, update it, and save it.

NSError *error = nil;//This is your NSManagedObject subclassBooks * aBook = nil;//Set up to get the thing you want to updateNSFetchRequest * request = [[NSFetchRequest alloc] init];[request setEntity:[NSEntityDescription entityForName:@"MyLibrary" inManagedObjectContext:context]];[request setPredicate:[NSPredicate predicateWithFormat:@"Title=%@",@"Bar"]];//Ask for itaBook = [[context executeFetchRequest:request error:&error] lastObject];[request release];if (error) {//Handle any errors}if (!aBook) {    //Nothing there to update}//Update the objectaBook.Title = @"BarBar";//Save iterror = nil;if (![context save:&error]) {           //Handle any error with the saving of the context}


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


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