插入操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// 创建托管对象,并指明创建的托管对象所属实体名 Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@ "Employee" inManagedObjectContext:context]; emp.name = @ "lxz" ; emp.height = @1.7; emp.brithday = [NSDate date]; // 通过上下文保存对象,并在保存前判断是否有更改 NSError *error = nil; if (context.hasChanges) { [context save:&error]; } // 错误处理 if (error) { NSLog(@ "CoreData Insert Data Error : %@" , error); } |
通过NSEntityDescription的insert类方法,生成并返回一个Employee托管对象,并将这个对象插入到指定的上下文中。
MOC将操作的数据存放在缓存层,只有调用MOC的save方法后,才会真正对数据库进行操作,否则这个对象只是存在内存中,这样做避免了频繁的数据库访问。
删除操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 建立获取数据的请求对象,指明对Employee实体进行删除操作 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@ "Employee" ]; // 创建谓词对象,过滤出符合要求的对象,也就是要删除的对象 NSPredicate *predicate = [NSPredicate predicateWithFormat:@ "name = %@" , @ "lxz" ]; request.predicate = predicate; // 执行获取操作,找到要删除的对象 NSError *error = nil; NSArray *employees = [context executeFetchRequest:request error:&error]; // 遍历符合删除要求的对象数组,执行删除操作 [employees enumerateObjectsUsingBlock:^(Employee * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { [context deleteObject:obj]; }]; // 保存上下文 if (context.hasChanges) { [context save:nil]; } // 错误处理 if (error) { NSLog(@ "CoreData Delete Data Error : %@" , error); } |
首先获取需要删除的托管对象,遍历获取的对象数组,逐个删除后调用MOC的save方法保存。
修改操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// 建立获取数据的请求对象,并指明操作的实体为Employee NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@ "Employee" ]; // 创建谓词对象,设置过滤条件 NSPredicate *predicate = [NSPredicate predicateWithFormat:@ "name = %@" , @ "lxz" ]; request.predicate = predicate; // 执行获取请求,获取到符合要求的托管对象 NSError *error = nil; NSArray *employees = [context executeFetchRequest:request error:&error]; [employees enumerateObjectsUsingBlock:^(Employee * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { obj.height = @3.f; }]; // 将上面的修改进行存储 if (context.hasChanges) { [context save:nil]; } // 错误处理 if (error) { NSLog(@ "CoreData Update Data Error : %@" , error); } |
和上面一样,首先获取到需要更改的托管对象,更改完成后调用MOC的save方法持久化到本地。
查找操作
1
2
3
4
5
6
7
8
9
10
11
12
|
// 建立获取数据的请求对象,指明操作的实体为Employee NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@ "Employee" ]; // 执行获取操作,获取所有Employee托管对象 NSError *error = nil; NSArray *employees = [context executeFetchRequest:request error:&error]; [employees enumerateObjectsUsingBlock:^(Employee * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSLog(@ "Employee Name : %@, Height : %@, Brithday : %@" , obj.name, obj.height, obj.brithday); }]; // 错误处理 if (error) { NSLog(@ "CoreData Ergodic Data Error : %@" , error); } |
查找操作最简单粗暴,因为是演示代码,所以直接将所有Employee表中的托管对象加载出来。在实际开发中肯定不会这样做,只需要加载需要的数据。后面还会讲到一些更高级的操作,会涉及到获取方面的东西。
总结
在CoreData中所有的托管对象被创建出来后,都是关联着MOC对象的。所以在对象进行任何操作后,都会被记录在MOC中。在最后调用MOC的save方法后,MOC会将操作交给PSC去处理,PSC将会将这个存储任务指派给NSPersistentStore对象。
上面的增删改查操作,看上去大体流程都差不多,都是一些最基础的简单操作,在下一篇文章中将会将一些比较复杂的操作。