Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update existing object in Core Data?

When I insert new object I do with following code:

NSManagedObjectContext *context = [appDelegate managedObjectContext];  Favorits *favorits = [NSEntityDescription insertNewObjectForEntityForName:@"Favorits" inManagedObjectContext:context];  favorits.title = @"Some title";  NSError *error;                     if (![context save:&error]) {     NSLog(@"Whoops"); } 

How can I update existing object in core data?

like image 256
iWizard Avatar asked May 13 '12 12:05

iWizard


People also ask

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.

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.


1 Answers

Updating is simple as creating a new one.

To update a specific object you need to set up a NSFetchRequest. This class is equivalent to a SELECT statetement in SQL language.

Here a simple example:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"Favorits" inManagedObjectContext:moc]];  NSError *error = nil; NSArray *results = [moc executeFetchRequest:request error:&error];  // error handling code 

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. For example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"]; [request setPredicate:predicate];  

In this case results contains the objects where title is equal to Some Title. Setting a predicate is equal to put the WHERE clause in a SQL statement.

For further info I suggest you to read the Core Data programming guide and NSFecthRequest class reference.

  • Core Data Programming Guide

  • NSFecthRequest Class Reference

Hope it helps.

EDIT (snippet that can be used to update)

// maybe some check before, to be sure results is not empty Favorits* favoritsGrabbed = [results objectAtIndex:0];     favoritsGrabbed.title = @"My Title";  // save here the context 

or if you are not using a NSManagedObject subclass.

// maybe some check before, to be sure results is not empty NSManagedObject* favoritsGrabbed = [results objectAtIndex:0]; [favoritsGrabbed setValue:@"My title" forKey:@"title"];  // save here the context 

In both cases if you do a save on the context, data will be updated.

like image 51
Lorenzo B Avatar answered Oct 07 '22 00:10

Lorenzo B