开发者

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


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/.


The only way to update multiple objects is to have all of those objects. There is no way to do "batch updating" with Core Data like you can in SQL, because Core Data is not a database. It is an object graph persistence framework, which means you will deal with objects.

There are tricks you can do to keep your memory usage down (such as batching your fetch request and only fetching certain properties), but ultimately you will be using a loop and updating the objects one-by-one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜