2

我正在使用 Core Data 将信息存储在我正在构建的 iPhone 应用程序中。

我打算将词汇对象存储在卡片组对象中,因此任何卡片组对象都可以有多个词汇表对象。

我想在我的词汇实体中创建一个属性“Deck ID”,并通过 ID 将词汇卡与卡片组相关联。但是,我不知道这是否是不好的做法?

有没有更好的方法来处理核心数据关系?据我所知,关系意味着 Deck Entity 只有一个 Vocabulary 对象,也许我错了。

我如何才能有效地构建适合我需要的核心数据结构?

谢谢。

4

2 回答 2

2

This is the correct way to do it. You can't "embed" an entity inside an entity.

If you want to have a deck entity that can have multiple instances of a vocabulary entity attached to it, you need to create separate entities for deck and vocabulary, and add a to-many relationship from your deck entity to your vocabulary entity, and a to-one relationship from your vocabulary entity back to your deck entity.

Here's a basic pair of entities in a Core Data model to demonstrate this:

Relationship

As you can see in the image, the Deck entity has a to-many relationship named vocabularies to the Vocabulary entity, with an inverse relationship deck.

The vocabularies relationship in the Deck entity is configured like so:

Relationship Configuration 1

and the deck relationship in the Vocabulary entity is configured like this:

Relationship Configuration 2

Note that the vocabularies relationship is to-many, while the deck relationship is not. This means that there can be multiple vocabularies for one Deck object, but each Vocabulary object can only be connected to one Deck object. This type of relationship is commonly represented as

Deck <---->> Vocabulary

which makes sense as you can see this is the same as the arrows in the image above connecting the two entities, denoting the type of relationship.

Core Data is at a higher level than interacting directly with a database (which it does for you), so you really don't need to think about it as a database. It's easier to think of Core Data as an object graph rather than a database, as this is what it represents: a collection of objects, connected to each other, not a set of disjoint tables that must be connected manually.

于 2013-06-18T07:18:10.917 回答
1

Core Data 学习曲线的一部分是停止将其视为关系数据库。

最好将其视为对象图 - 对象链接在一起的方式,而不是由标识符连接的表。

在您的情况下,您应该做的是拥有一个卡片组对象和一个词汇表对象并设置如下关系:

deck <-->> vocabulary

(当人们谈论 Core Data 时,你会经常看到这种表示法)

这意味着卡片组对象与词汇对象具有一对多的关系,而词汇对象与卡片组对象具有一对一的关系。在 CD 中,这种关系是双向的。

如果您这样做,则无需手动创建 id 和连接对象的表,它将在内部为您管理。您需要做的就是在关系中添加和删除对象。对于 Vocabulary 对象,这将只是一个卡片组类型的对象,而对于卡片组,它将是一组词汇类型的对象。具有双向关系意味着,例如,如果您创建一个词汇对象并将其分配给一个卡片组,那么卡片组对象将自动将此词汇对象添加到其词汇对象集中。

于 2013-06-18T07:25:18.020 回答