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
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.
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With