Coy Coy - 1 year ago 49
Objective-C Question

What is the most efficient way to update the value of all or some managed objects in Core Data in Objective-C

I've googled and researched but am not able to find the best way to iterate through all or some managed objects in my Data Model and update an attribute value in each of them, in my situation, update to the current date. The managed object context and persistent store delegate methods are all in my Application Delegate. I could add some code in a table view in the program but I feel it would be more efficient to call method to update these values, as they may not necessarily return to the table view.

Ultimately I want to loop through my managed objects and update values as I go through the loop, from anywhere in my application.

Please let me know if you require any more information. Thanks!



Depending on what you want to update the values to, you could fetch an array of objects and call setValue:forKey: on the array, which would set the value for every object in the array. e.g.:

//fetch managed objects
NSArray *objects = [context executeFetchRequest:allRequest error:&error];
[objects setValue:newValue forKey:@"entityProperty"];
//now save your changes back.
[context save:&error];

Setting up the fetch request should just require the entity you want, leave the predicate nil so that you get all instances back.