1. 创建Data Model
鼠标右键弹出菜单,选择New File,再选择Core Data下的Data Model,创建xcdatamodeld
类型的文件
Data Model中,点击Add Entity
按钮,创建新的Entity,并在Attributes下设置属性
2. 创建上下文
导入库和设置属性
#import <CoreData/CoreData.h>
@property (nonatomic, strong) NSManagedObjectContext *context;
创建上下文
// 创建模型文件
NSURL *url = [[NSBundle mainBundle] URLForResource:@"xcdatamodeld文件名" withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
// 设置持久化存储协调器
NSPersistentStoreCoordinator *coord = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSURL *url = [NSURL fileURLWithPath:@"database存储路径"];
NSError *error = nil;
[coord addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
if (error != nil) {
NSLog(@"CoreDataManager init\n%@", error);
}
// 创建上下文
self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
self.context.persistentStoreCoordinator = coord;
创建模型
#import <CoreData/CoreData.h>
@interface ManagedObject : NSManagedObject
@property (nonatomic, copy) NSString *username;
@property (nonatomic, copy) NSString *password;
@end
添加操作
ManagedObject *mo = [NSEntityDescription insertNewObjectForEntityForName:@"Client" inManagedObjectContext:self.context];
mo.username = ...
mo.password = ...
保存
NSError *error = nil;
[self.context save:&error];
if (error != nil) {
NSLog(@"%@", error);
}