CoreData初始化过程
在使用coreData之前需要在工程中导入coreData.framework框架,在导入框架后开始设计实体模型
New File ->Core Data ->Data Mode.....l完成CoreData实体模型的创建并生成一个NSManagedObject子类并通过这个子类对数据库进行操作
一、创建模型对象
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
二、创建模型协调器
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
三、设置数据库存储路径
NSString *pathSQLite = [NSString stringWithFormat:@"%@/Documents/data.sqlite",NSHomeDirectory()];
四、设置封装的类型
[coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:path] options:nil error:nil];
五、创建管理上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
六、设置上下文的协调器
context.persistentStoreCoordinator = coordinator;
经过上面的步骤一个CoreData核心API的初始化完成,如果说数据库存储路径下已经有啦相同名字的数据库文件,系统会自动加载已有的数据库而不会去创建新的数据库文件
CoreData的增、删、改、查
一、增
1、创建一个实体模型对象
Mymodel *myModel = [NSEntityDescription insertNewObjectForEntityForName:@"Mymodel" inManagedObjectContext:context];
2 、往数据库中添加数据并保存
Mymodel *myModel = [NSEntityDescription insertNewObjectForEntityForName:@"Mymodel" inManagedObjectContext:_context];
myModel.name = @"张三";
if ([context save:nil]) {
NSLog(@"保存成功");
} else {
NSLog(@"保存失败");
}
如果[context save:nil]为真则保存成功,反之失败
二、删