How to update an existing object in Core Data?

When I insert a new object, I do the 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 to update an existing object in the master data?

+58
objective-c core-data
May 13 '12 at 12:39
source share
5 answers

Updating is as simple as creating a new one.

To update a specific object, you need to configure NSFetchRequest . This class is equivalent to the SQL SELECT statement.

Here is 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 results array contains all of the managed objects contained in the sqlite file. If you want to get a specific object (or several objects), you need to use a predicate with this query. For example:

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

In this case, the results contain objects where the title is Some Title . Setting a predicate equals putting a WHERE clause in an SQL statement.

For more information, I suggest you read the Core Data programming guide and the NSFecthRequest class NSFecthRequest class.

Hope it helps.

EDIT (fragment that can be used for updating)

 // 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 subclass of NSManagedObject .

 // 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 save context, the data will be updated.

+128
May 13, '12 at 13:28
source share

You have to fetch the object from the context, change the properties you want, and then save the context, as in your example.

+11
May 13 '12 at 13:16
source share

Hope this helps you. how it works for me.

  NSMutableArray *results = [[NSMutableArray alloc]init]; int flag=0; NSPredicate *pred; if (self.txtCourseNo.text.length > 0) { pred = [NSPredicate predicateWithFormat:@"courseno CONTAINS[cd] %@", self.txtCourseNo.text]; flag=1; } else { flag=0; NSLog(@"Enter Corect Course number"); } if (flag == 1) { NSLog(@"predicate: %@",pred); NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Course"]; [fetchRequest setPredicate:pred]; results = [[self.context executeFetchRequest:fetchRequest error:nil] mutableCopy]; if (results.count > 0) { NSManagedObject* favoritsGrabbed = [results objectAtIndex:0]; [favoritsGrabbed setValue:self.txtCourseName.text forKey:@"coursename"]; [self.context save:nil]; [self showData]; } else { NSLog(@"Enter Corect Course number"); } } 
+7
Jul 25 '15 at 6:28
source share

I saw an answer in Objective-C that helped me. I am posting an answer for Swift users -

  let updateCont = appDelegate?.persistentContainer.viewContext let pred = NSPredicate(format: "your_Attribute_Name = %@", argumentArray : [your_Arguments]) let request = NSFetchRequest<NSFetchRequestResult>(entityName: "your_Entity_Name") request.predicate = pred do { let resul = try updateCont?.fetch(request) as? [NSManagedObject] let m = resul?.first m?.setValue(txtName.text, forKey: "your_Attribute_Name_Whose_Value_Should_Update") try? updateCont?.save() }catch let err as NSError { print(err) } 
0
Jun 12 '19 at 5:44
source share

If you are a fast programmer, this can help you:

if you want to remove NSManagedObject

in my case, the Identifier is a unique attribute for the STUDENT object

 /** for deleting items */ func Delete(identifier: String) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT") let predicate = NSPredicate(format: "ID = '\(identifier)'") fetchRequest.predicate = predicate do { let object = try context.fetch(fetchRequest) if object.count == 1 { let objectDelete = object.first as! NSManagedObject context.delete(objectDelete) } } catch { print(error) } } 

if you want to update NSManagedObject:

 /** for updating items */ func Update(identifier: String,name:String) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT") let predicate = NSPredicate(format: "ID = '\(identifier)'") fetchRequest.predicate = predicate do { let object = try context.fetch(fetchRequest) if object.count == 1 { let objectUpdate = object.first as! NSManagedObject objectUpdate.setValue(name, forKey: "name") do{ try context.save() } catch { print(error) } } } catch { print(error) } } 
-one
May 22 '18 at 4:36
source share



All Articles