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

I searched googled and researched, but cannot find a better way to repeat all or some of the managed objects in my data model and update the attribute value in each of them, in my situation, update the current date. The managed object context and persistent methods for delegating storage are in my application. I could add some code to the table view in the program, but I believe that it would be more efficient to call a method to update these values, since they may not necessarily return to the table view.

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

Please let me know if you need more information. Thanks!

-Coy

+7
objective-c iphone core-data managed
source share
3 answers

Depending on what you want to update the values, you can get an array of objects and call setValue: forKey: in the array that set the value for each object in the array. eg:.

//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 a fetch request requires only the required object, leave the nil predicate to return all instances.

+11
source share

The only way to update multiple objects is to have all of these objects. It is not possible to perform a “batch upgrade” using Core Data, as you can in SQL, because Core Data is not a database. This is an object-oriented structure, which means that you will be dealing with objects.

There are tricks that you can do to save memory usage (for example, a batch request for fetching and only fetching certain properties), but in the end you will use a loop and update the objects one at a time.

+4
source share

Starting with iOS 8 and OS X 10.10 (Yosemite), Apple has added a new class in Core Data to perform batch updates: NSBatchUpdateRequest . This is significantly more efficient than using NSFetchRequest , especially when working with large amounts of data. Here is an 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 topic: https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/ .

+4
source share

All Articles