如何创建许多临时对象,然后只使用Core Data保存一个? [英] How do I create many temporary objects and then save only one using Core Data?

查看:151
本文介绍了如何创建许多临时对象,然后只使用Core Data保存一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,它将对在线服务执行搜索,并生成许多结果对象。结果对象是一个NSManagedObject,根据需要通过与NSManagedObjectContext关联来初始化。

I am working on an application that will perform a search against an online service and generate many Result objects. A Result object is an NSManagedObject, initialized as required by associating it with an NSManagedObjectContext.

用户应该能够选择一个结果并将其保存为 。在应用程序中,这很简单,将Result实体与一个新的Favorite实体关联并保存上下文。

Users should be able to select a "Result" and save it as a "Favorite". In the application this is as simple as associating the Result entity with a new Favorite entity and saving the context.

问题是,上下文中的每一个Result都会得到

The problem is that every single Result in the context of course gets saved to the database along with the one I want Favorited.

我已经看到过许多使用多个NSManagedObjectContext实例来管理各种创建和持久性情况的例子。所有这些都似乎围绕着创建一个上下文的新实例,然后将它们合并到另一个上下文中,以避免另一个FetchRequest执行的想法。这些示例不解决问题,因为它们仍然导致每个Result实体被保存。

I've seen many examples of using multiple NSManagedObjectContext instances to manage various creation and persistence situations. All of them seem to revolve around the idea of creating new instances with one Context and then merging them on save into another context for the sake of avoiding another FetchRequest execution. These examples don't solve the problem as they still lead to every Result entity being saved.

任何人有任何建议?

推荐答案

您应该为每个对象使用不同的上下文。使用单独的受管对象上下文允许您按如下方式工作。当用户选择其最喜欢的对象时,您只需丢弃与其余结果对象相关的上下文。不需要合并更改等。基本上有一个权衡。你最终管理(创建/丢弃)几个上下文,但随后你很容易完成你的目标。否则,你仍然可以使用一个单一的上下文。但是,您必须显式插入或删除每个对象,如以下代码段所示。

You should use a different context for each object. Using a separate managed object context allows you to work as follows. When the user selects its favorite object, you just discard the contexts related to the remaining result objects. No need to merge changes etc. There is basically a tradeoff. You end up managing (creating/discarding) several contexts, but then you accomplish your goal easily. Otherwise, you can still do this using just a single context. However, you have to explicitly insert or delete each object as shown in the following code snippets.

尝试此操作。只对要保存的收藏对象,执行以下操作:

Try this. Only for the favorite object you want to save, do the following:

[managedObjectContext insertObject:theFavorite];

对于其他每个结果对象都会这样做:

For each of the other result objects do this instead:

[managedObjectContext deleteObject:aResult];

然后另存为

NSError *error = nil
if (![managedObjectContext save:&error]) {
   // Handle error

}

这将仅保存您选择的收藏对象。

This will save ONLY your selected, favorite object.

这篇关于如何创建许多临时对象,然后只使用Core Data保存一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆