在定义好数据层模型和初始化Core Data协议栈后,我们已经可以开始创建可用于持久存储的数据对象了。
After you have defined your managed object model and initialized the Core Data stack within your application, you are ready to start creating objects for data storage.
创建数据对象
Creating Managed Objects
NSManagedObject
类中定义了一系列访问Core Data数据模型需要的基本方法。每一个NSManagedObject
对象都包含两个基本元素:数据结构描述对象( NSEntityDescription
)和数据容器对象(NSManagedObjectContext
)。数据结构描述对象定义了数据对象的名字、所包含的字段和关系。数据容器存储内存中的数据影像、维护数据修改记录和对象间关系。
An NSManagedObject
instance implements the basic behavior required of a Core Data model object. The NSManagedObject
instance requires two elements: an entity description (an NSEntityDescription
instance) and a managed object context (an NSManagedObjectContext
instance). The entity description includes the name of the entity that the object represents and its attributes and relationships. The managed object context represents a scratch pad where you create the managed objects. The context tracks changes to and relationships between objects.
在下面的示例代码中,NSEntityDescription
类根据数据表名和数据容器句柄创建了一个EmployeeMO
类型的数据对象。
As shown in this example, the NSEntityDescription
class has a class method that accepts a string for the name of the entity and a reference to the NSManagedObjectContext
that the NSManagedObject
instance will be associated with. The example defines the returning object as an EmployeeMO
object.
OBJECTIVE-C
-----------
AAAEmployeeMO *employee = [NSEntityDescription
insertNewObjectForEntityForName:@"Employee"
inManagedObjectContext:[self managedObjectContext];
SWIFT
-----
let employee = NSEntityDescription.insertNewObjectForEntityForName(
"Employee",
inManagedObjectContext: managedObjectContext
) as! EmployeeMO
自定义NSManagedObject 子类
Creating NSManagedObject Subclasses
一般情况下,我们会为所有的数据表都创建一个数据类,继承自NSManagedObject
。我们可以在这个类中定义对应字段和关系的属性变量,并封装一些辅助方法。
By default, Core Data returns NSManagedObject
instances to your application. However, it is useful to define subclasses of NSManagedObject
for each of the entities in your model. Speciflcally, when you create subclasses of NSManagedObject
, you can define the properties that the entity can use for code completion, and you can add convenience methods to those subclasses.
创建数据子类,除了在在Xcode中手动创建NSManagedObject
的子类,还需要将类名注册进数据层模型中去。我们可以在Xcode的数据层模型编辑器中选择数据表,在属性面板中的Class编辑项中填写类名。
To create a subclass of NSManagedObject
, in the Xcode Core Data model editor, select the entity, and in the Entity pane of the Data Model inspector, enter the name in the Class field. Then create the subclass in Xcode.
OBJECTIVE-C
-----------
#import
@interface AAAEmployeeMO : NSManagedObject
@property (nonatomic, strong) NSString *name;
@end
-----------
@implementation AAAEmployeeMO
@dynamic name;
@end
SWIFT
-----
import UIKit
import CoreData
import Foundation
class EmployeeMO: NSManagedObject {
@NSManaged var name: String?
}
@dynamic(@NSManaged)标签告诉编译器此变量在运行态才会被分配。
The @dynamic(@NSManaged) tag informs the compiler that the variable will be resolved at runtime.
你可以在你的应用程序中,直接通过NSManagedObject
的子类来访问数据对象,使你的代码更具可读性。
After the subclass has been defined in your data model and added to your project, you can reference it directly in your application and improve the readability of your application code.
保存数据对象
Saving NSManagedObject Instances
NSManagedObject
对象的创建,并不意味着相关数据已经记录在外部存储器中,我们必须显式地调用保存方法才能完成这个过程。
The creation of NSManagedObject
instances does not guarantee their persistence. After you create an NSManagedObject
instance in your managed object context, explicitly save that context to persist those changes to your persistent store.
OBJECTIVE-C
-----------
NSError *error = nil;
if ([[self managedObjectContext] save:&error] == NO) {
NSAssert(NO, @"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
}
SWIFT
-----
do {
try managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
执行NSManagedObjectContext
的save
方法可以接受一个NSError
变量,用于返回结果。如果成功,则不需要去关注这个变量。如果失败,最好将变量中的错误信息显示出来用于纠错。我们可以简单的将错误信息打印出来,也可以显示在用户界面上。
The call to save on the NSManagedObjectContext
accepts a reference to an NSError
variable and always returns either a success or a fail. If the save fails, it is important to display the error condition so that it can be corrected. The display of that error condition can be as simple as outputting the error to the console or as complicated as offering the error message to the user. If the save method returns a success, the error variable does not need to be consulted.