Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

-Coy

like image 647
Coy Avatar asked Oct 19 '10 20:10

Coy


2 Answers

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.

like image 96
ImHuntingWabbits Avatar answered Oct 07 '22 09:10

ImHuntingWabbits


Starting with iOS 8 and OS X 10.10 (Yosemite), Apple added a new class in Core Data for performing batch updates: NSBatchUpdateRequest. It is considerably more efficient than the solution using an NSFetchRequest, particularly when dealing with large amounts of data. Here is a basic example:

NSBatchUpdateRequest *batchUpdate = [[NSBatchUpdateRequest alloc] initWithEntityName:@"EntityName"];
batchUpdate.propertiesToUpdate = @{ @"attribute": @(0) };
batchUpdate.resultType = NSStatusOnlyResultType;
[managedObjectContext executeRequest:batchUpdate error:nil];

And here's a good blog post on the subject: https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/.

like image 34
newenglander Avatar answered Oct 07 '22 08:10

newenglander