CoreData就是对象模型和关系模型的互转,如下图:
模型文件:
在Core Data,需要进行映射的对象称为实体(entity);下面新建一个模型文件:
程序步骤:
1.新建模型文件
2.上代码
property(nonatomic, strong) NSManagedObjectContext *context;
初始化上下文:
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 构建SQLite数据库文件的路径
NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.data"]];
NSLog(@"%@",url);
// 添加持久化存储库,这里使用SQLite作为存储库
NSError*error =nil;
NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
if(store ==nil) {// 直接抛异常
[NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]];
}
// 初始化上下文,设置persistentStoreCoordinator属性
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:0];
self.context= context;
context.persistentStoreCoordinator = psc;
插入数据:
-(void)addinto{
// 传入上下文,创建一个Person实体对象
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
// 设置Person的简单属性
[personsetValue:@"MJ"forKey:@"name"];
[personsetValue:[NSNumber numberWithInt:27] forKey:@"age"];
// 传入上下文,创建一个Card实体对象
NSManagedObject *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:self.context];
[cardsetValue:@"4414241933432" forKey:@"no"];
// 设置Person和Card之间的关联关系
[personsetValue:cardforKey:@"card"];
// 利用上下文对象,将数据同步到持久化存储库
NSError*error =nil;
BOOLsuccess = [self.contextsave:&error];
if(!success) {
[NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
}
}
查询:
-(void)query{
// 初始化一个查询请求
NSFetchRequest *request = [[NSFetchRequest alloc] init];
// 设置要查询的实体
request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
// 设置排序(按照age降序)
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sort];
// 执行请求
NSError*error =nil;
NSArray*objs = [self.contextexecuteFetchRequest:requesterror:&error];
if(error) {
[NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
}
// 遍历数据
for (NSManagedObject *obj in objs) {
NSLog(@"name=%@", [objvalueForKey:@"name"]);
}
}