在 Objective-C 中更新 Core Data 中所有或部分托管对象的值的最有效方法是什么
我已经用谷歌搜索和研究,但无法找到迭代数据模型中的所有或部分托管对象并更新每个对象中的属性值的最佳方法,在我的情况下,更新到当前日期。托管对象上下文和持久存储委托方法都在我的应用程序委托中。我可以在程序的表视图中添加一些代码,但我觉得调用方法来更新这些值会更有效,因为它们不一定返回到表视图。
最终,我想从应用程序中的任何位置循环遍历我的托管对象并在循环时更新值。
如果您需要更多信息,请告诉我。谢谢!
-腼腆
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您想要更新值的内容,您可以获取对象数组并在数组上调用 setValue:forKey: ,这将为数组中的每个对象设置值。例如:
设置获取请求应该只需要您想要的实体,将谓词保留为 nil,以便您获取所有实例。
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.:
Setting up the fetch request should just require the entity you want, leave the predicate nil so that you get all instances back.
从 iOS 8 和 OS X 10.10 (Yosemite) 开始,Apple 在 Core Data 中添加了一个新类,用于执行批量更新:
NSBatchUpdateRequest
。它比使用 NSFetchRequest 的解决方案要高效得多,特别是在处理大量数据时。这是一个基本示例:这是关于该主题的一篇很好的博客文章:https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/。
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 anNSFetchRequest
, particularly when dealing with large amounts of data. Here is a basic example:And here's a good blog post on the subject: https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/.
更新多个对象的唯一方法是拥有所有这些对象。无法像在 SQL 中那样使用 Core Data 进行“批量更新”,因为 Core Data 不是数据库。它是一个对象图持久性框架,这意味着您将处理对象。
您可以采取一些技巧来降低内存使用量(例如批量获取请求并仅获取某些属性),但最终您将使用循环并逐一更新对象。
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.