Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Update an attribute in Core Data

Tags:

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.

like image 694
joshwbrick Avatar asked Jan 10 '09 21:01

joshwbrick


People also ask

How do you update an object in Core Data?

To update a specific object you need to set up a NSFetchRequest . This class is equivalent to a SELECT statetement in SQL language. The array results contains all the managed objects contained within the sqlite file. If you want to grab a specific object (or more objects) you need to use a predicate with that request.

What is NSManagedObject in Core Data?

Data Storage In some respects, an NSManagedObject acts like a dictionary—it's a generic container object that provides efficient storage for the properties defined by its associated NSEntityDescription instance.

What is attribute in Core Data?

You can think of attributes as the columns of a table in a database. Attributes store the values of a Core Data record. There are several types of attributes, such as String, Date, Integer, Float, and Boolean. Select the Note entity in the data model editor and click the + button at the bottom of the Attributes table.

How do I update my class in NSManagedObject?

You can do this: Choose "Create NSManagedObject Subclass…" from the Core Data editor menu to delete and recreate this implementation file for your updated model. You will then remove the files you already had, and the new ones will be created.


1 Answers

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 subclass
Books * aBook = nil;

//Set up to get the thing you want to update
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"MyLibrary" inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"Title=%@",@"Bar"]];

//Ask for it
aBook = [[context executeFetchRequest:request error:&error] lastObject];
[request release];

if (error) {
//Handle any errors
}

if (!aBook) {
    //Nothing there to update
}

//Update the object
aBook.Title = @"BarBar";

//Save it
error = nil;
if (![context save:&error]) {
           //Handle any error with the saving of the context
}
like image 152
giff Avatar answered Oct 07 '22 22:10

giff