美文网首页
Core Data编程指南 1-2:创建数据对象模型

Core Data编程指南 1-2:创建数据对象模型

作者: TalktoEason | 来源:发表于2017-07-17 18:42 被阅读0次

Core Data的大部分功能依赖于数据层模型(managed object model)的定义。这个模型以NSManagedObjectModel对象的形式存在,主要描述了应用程序中使用到的各种数据表、数据对象及属性、对象间关系等信息。一个完备的数据层模型能更好支持应用程序的功能实现。

Much of Core Data’s functionality depends on the schema you create to describe your application’s entities, their properties, and the relationships between them. Core Data uses a schema called a managed object model — an instance of NSManagedObjectModel. In general, the richer the model, the better Core Data is able to support your application.

数据层模型的主要功能是将存储在外部存储设备上的数据记录(records),映射成应用程序中的数据对象(managed objects)。它由一些数据描述项(entity description, 对应NSEntityDescription对象)组成,相当于数据库概念中的数据表。数据描述项定义了数据表的名字、对应程序中的数据类名、以及表中数据对象的属性和关系。

A managed object model allows Core Data to map from records in a persistent store to managed objects that you use in your application. The model is a collection of entity description objects (instances of NSEntityDescription). An entity description describes an entity (which you can think of as a table in a database) in terms of its name, the name of the class used to represent the entity in your application, and what properties (attributes and relationships) it has.

创建数据表并定义其属性
Creating an Entity and Its Properties

在Xcode中创建项目的时候,在模板对话框中选中“Use Core Data”复选框,可以在项目中生成一个扩展名为.xcdatamodeld的Core Data模板文件。在导航面板中选中此文件将会打开一个Core Data数据模型编辑窗口。

When you start a new project in Xcode and open the template selection dialog, select the Use Core Data checkbox. A source file for the Core Data model is created as part of the template. That source file will have the extension .xcdatamodeld. Select that file in the navigator area to display the Core Data model editor.

建立数据表
To create an entity

  1. 点击“Add Entity”按键。
    Click Add Entity.

    导航区的数据表列表中会出现一个新的未命名数据表。

    A new untitled entity appears in the Entities list in the navigator area.

  2. 选中这个新的数据表项。
    Select the new untitled entity.

  3. 在属性区的数据表页面中输入表名,并回车。
    In the Entity pane of the Data Model inspector, enter the name of the entity, and press Return.

在数据表中创建字段(Attribute)和关系(Relationship)
To create attributes and relationships for the entity

  1. 选中数据表后,点击底部的“Add Attribute”(+)键

    With the new entity selected, click the Add button (+) at the bottom of the appropriate section.

    编辑区域的字段或关系列表中会出现一个新的未命名字段或者关系(“字段”和“关系”通常统称为“属性”)。

    A new untitled attribute or relationship (generically referred to as a property) is added in the Attributes or Relationships section of the editor area.

  2. 选中新属性

    Select the new untitled property.

    属性面板中会显示出相应的字段或关系设置页面。

    The property settings are displayed in the Relationship pane or Attribute pane of the Data Model inspector.

  3. 输入属性名,回车确认

    Give the property a name, and press Return.

    字段或者关系的信息会显示在编辑区域

    The attribute or relationship information appears in the editor area.

如下图2-1 编辑雇员数据表 定义了一个雇员信息数据表,包括了用户名、出生日期和入职时间等字段

Employee entity in the Xcode Data Model editor shows an entity called Employee, with attributes that describe the employee: date of birth, name, and start date.

图2-1 编辑雇员数据表 <br>_Figure 2-1 Employee entity in the Xcode Data Model editor_

至此,我们已经建立了一个空数据表。表中的数据会在应用程序运行的时候,以数据对象(managed objects, NSManagedObject 对象)的形式创建出来。

At this point you have created an entity in the model, but you have not created any data. Data is created later, when you launch your application. These entities will be used in your application as the basis for the creation of managed objects ( NSManagedObject instances).

完善数据表
Defining an Entity

在之前的章节中,我们已经生产了一个命了名的数据表,现在需要在属性面板中更进一步的完善它(参考 图2-2 数据表的属性设置)。

Now that you have named your entity, you define it further in the Entity pane of the Data Model inspector; see Entity pane in the Data Model inspector.

图2-2 配置数据表 <br>_Figure 2-2 Entity pane in the Data Model inspector_

表字和类名
Entity Name and Class Name

数据表名和对应的数据类名(必须扩展自NSManagedObject类)是必须配置的属性。图2-2中的类名(EmployeeMO)是一个符合Objective-C命名规则的名字,以MO结尾,代表是一个数据对象。表名和类名并不是等同的,它们作用与不同的领域。表的继承关系也并不需要和对应类的继承关系相吻合。

Note that the entity name and the class name (a subclass of NSManagedObject) are not the same. The entity structure in the data model does not need to match the class hierarchy. Figure 2-2 shows a class name with the recommended class name pattern of Objective-C, along with an MO suffix. An entity name and a class name are required.

抽象表
Abstract Entities

我们将不需要实例化的数据表称为抽象表。当大量的数据表中都存在类似的一个通用结构,我们通常会建立一个不需要实例化的抽象表。例如在雇员数据库中,我们可以定义了Person抽象表。这个表并没有对应的实例化对象,而仅仅被其他表继承(比如Employee和Customer表)。Core Data会保证抽象表永远不会被实例化。

Specify that an entity is abstract if you will not create any instances of that entity. You typically make an entity abstract if you have a number of entities that all represent specializations of (inherit from) a common entity that should not itself be instantiated. For example, in the Employee entity you could define Person as an abstract entity and specify that only concrete subentities (Employee and Customer) can be instantiated. By marking an entity as abstract in the Entity pane of the Data Model inspector, you are informing Core Data that it will never be instantiated directly.

数据表的继承关系
Entity Inheritance

数据表继承和类继承非常相似。如果有一系列的数据表在结构上非常相似,你可以把这些相似的属性抽象出来,建立一个父表。我们可以在一个父表中定义通用属性,由其他表中继承过去;而不是在几个表中重复定义相同的属性。例如,你可以定义一个Person表,包括姓、名等属性,由Employee和Customer表来继承。图2-3 数据表继承示意图展示了一个这样的例子。在编辑窗口的右下角点击”Editor Style“按键,可以显示当前所有表的继承结构。

Entity inheritance works in a similar way to class inheritance; and is useful for the same reasons. If you have a number of entities that are similar, you can factor the common properties into a superentity, also known as a parent entity. Rather than specifying the same properties in several entities, you can define them in one entity, and the subentities inherit them. For example, you might define a Person entity with attributes firstName and lastName, and subentities Employee and Customer, which inherit those attributes. An example of this layout is shown in Figure 2-3. Display the layout diagram by clicking the Editor Style buttons in the lower-right corner.

图2-3 数据表继承示意图 <br>_Figure 2-3 Entity inheritance diagram_

在大多数情况下,对应数据表的数据类也存在相同的继承关系。你可以在一个类中定义通用的事务逻辑,继承到其他的子类中去,而不是在不同类中重复定义相似的事物逻辑。

In many cases, you also implement a custom class to correspond to the entity from which classes representing the subentities also inherit. Rather than implementing business logic common to all the entities several times over, you implement them in one place and they are inherited by the subclasses.

备注 NOTE

当使用SQLite作为外部存储器接口时,必须非常小心的使用数据表的继承关系。所有继承自同一个父表的数据会被SQLite放在同一个数据表中,从而有可能导致一些运行速度问题。

Be careful with entity inheritance when working with SQLite persistent stores. All entities that inherit from another entity exist within the same table in SQLite. This factor in the design of the SQLite persistent store can create a performance issue.

定义字段和关系
Defining Attributes and Relationships

一个数据表由若干属性组成,这里“属性”又分为字段(Attribute)、表间的关系(Relationship)和查询属性(fetched properties)。每一个属性都有一个专有名字和属性类型。属性名不能和NSObject 或者NSManagedObject的任何一个无参方法名雷同 -- 比如“description”不能当成任何一个字段或者关系的名字(参考NSPropertyDescription类)。

An entity’s properties are its attributes and relationships, including its fetched properties (if it has any). Among other features, each property has a name and a type. A property name cannot be the same as any no-parameter method name of NSObject or NSManagedObject — for example, you cannot give a property the name “description” (see NSPropertyDescription).

在数据模型中有一类属性叫临时属性(Transient attributes),它不会被保存在 外部存储器中。Core Data依然会维护这类属性的修改历史,并支持Undo操作。这类属性通常用于保存计算中间值(calculated values)或者继承下来的中间值(derived values)。

Transient attributes are properties that you define as part of the model, but that are not saved to the persistent store as part of an entity instance’s data. Core Data does track changes you make to transient properties, so they are recorded for undo operations. You use transient properties for a variety of purposes, including keeping calculated values and derived values.

备注 NOTE

如果你对一个临时属性使用Undo操作,Core Data并不会调用数据对象的设置方法(set accessor)来设置属性值,而是直接将数据对象恢复到之前的快照。

If you undo a change to a transient property that uses nonmodeled information, Core Data does not invoke your set accessor with the old value — it simply updates the snapshot information.

字段
Attributes

选择编辑窗口中的某个字段,可以在属性面板中进行相关配置,参见图2-4 字段配置页面。Core Data支持一些原生的字段类型,如字符串、日期和整数等(对应数据类为NSStringNSDateNSNumber)。

_To define an attribute, select it in the Core Data model editor and specify values in the Attribute pane of the Core Data Model inspector; see Attribute pane in the Data Model inspector. Core Data natively supports a variety of attribute types, such as string, date, and integer (represented as instances of NSString, NSDate, and NSNumber respectively). _

图2-4 字段配置页面<br>_Figure 2-4 Attribute pane in the Data Model inspector_

标注成可选(optional)的字段可以置空(NULL),但我们应该尽量少使用这个功能。在SQL系统中,NULL值的处理和Objective-C的nil不同。它并不等同与数值0,甚至不等同与一个空字符串,或者一个空数据块。搜索0值并不会返回空字段。为了避免一些不必要的问题,我们可以用一个缺省值(通常是0)来代替NULL,特别是数值类型的字段。

You can specify that an attribute is optional—that is, it is not required to have a value. In general, however, avoid doing so, especially for numeric values. Typically, you can get better results using a mandatory attribute with a default value—defined in the attribute—of 0. The reason for this is that SQL has special comparison behavior for NULL that is unlike Objective-C’s nil. NULL in a database is not the same as 0, and searches for 0 do not match columns with NULL. Moreover, NULL in a database is not equivalent to an empty string or empty data blob.

关系和查询属性
Relationships and Fetched Properties

要配置一个关系,只需在编辑窗口中选择这个关系,然后在属性面板中进行配置。参见图2-5 关系配置页面

To define a relationship, select it in the Core Data model editor, and specify values in the Relationship pane of the Data Model inspector; Relationship in the Data Model inspector.

图2-5 关系配置页面 <br>_Figure 2-5 Relationship pane in the Data Model inspector_

Core Data支持两种不同类型的关系: to-one 和 to-many,和一种查询属性。查询属性是一种单向的“弱关系”。对于employees 和departments 这个例子来说,department 可能会存在一个“recent hires”的查询属性(employees 并不会存在一个类似的反向属性)。

Core Data supports to-one and to-many relationships, and fetched properties. Fetched properties represent weak, one-way relationships. In the employees and departments domain, a fetched property of a department might be “recent hires” (employees do not have an inverse to the recent hires relationship).

定义关系的时候需要在Type下拉框中选择关系类型,to-one或者是to-many。关系类型是存在方向性的,但我们也可以通过两个相反的to-many关系定义一个many-to-many的无方向关系。

The Type pop-up menu defines whether the relationship is a to-one type relationship or a to-many type relationship. Relationships are defined from one direction at a time. To create a many-to-many relationship, you would need to create two to-many relationships and then set them up as inverses of each other.

Destination下拉框定义的是关系目标对象的类名。在获取关系对象的时候,如果是一个to-one关系,会返回一个单独的数据对象(如果关系是Optional的,也可能是nil);如果是一个to-many的一对多关系,则会返回一个集合(或者也可能是nil)。

The Destination pop-up menu defines what object (or objects) is returned when the relationship is accessed in code. If the relationship is defined as to-one, a single object (or nil if the relationship can be optional) is returned. If the relationship is defined as to-many, a set is returned (or again, nil if the relationship can be optional).

每个关系项仅代表了关系的一个方向,每个关系都是由两个关系项组成的。Inverse下拉框中指定了对应的另一半关系项,将两个单向的关系项合成一个完整的关系。

The Inverse pop-up menu defines the other half of a relationship. Because each relationship is defined from one direction, this pop-up menu joins two relationships together to create a fully bidirectional relationship.

后面在创建数据对象关系一章中将会更详细的介绍关系。

Relationships are described in greater detail in Creating Managed Object Relationships.

相关文章

网友评论

      本文标题:Core Data编程指南 1-2:创建数据对象模型

      本文链接:https://www.haomeiwen.com/subject/yjjfkxtx.html