Core Data数据持久化的使用
CoreData 是ios中用来对数据做持久化的一个框架,它对sqlite进行了封装,使我们不需要学习数据库知识,也不要写SQL语句就能将数据保存到数据库。下面来介绍CoreData的如何使用。
1. 新建一个项目,勾选使用Core Data, 新建后需要导入:CoreData.framework
2.新建项目后,AppDelegate类会生成三个属性
- @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
- @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
- @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
这三个对象操作数据会用的到。
3.新建一个实体对象
4. 创建一个类与实体对象关联
5. 保存一个实体模型对象
- Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
- person.personId = @10002;
- person.age = @29;
- person.name = [NSString stringWithFormat:@"jack"];
- NSError *error = nil;
- BOOL ret = [self.managedObjectContext save:&error];
- if (ret) {
- NSLog(@"保存成功!");
- } else {
- NSLog(@"error");
- }
6.删除一个实体模型对象
- //删除
- - (void)modifyPerson {
- NSEntityDescription *entifyDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
- NSFetchRequest *fetchReqeust = [[NSFetchRequest alloc] init];
- [fetchReqeust setEntity:entifyDesc];
- //查询年龄大于30的实体person对象
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.age=30"];
- [fetchReqeust setPredicate:predicate];
- //查询出来的person对象数组
- NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchReqeust error:nil];
- //遍历删除
- for (Person *p in persons) {
- [self.managedObjectContext deleteObject:p];
- }
- }
7. 查询
- //根据条件查询数据
- - (void)queryPerson {
- NSEntityDescription *entifyDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
- //查询对象
- NSFetchRequest *fetchReqeust = [[NSFetchRequest alloc] init];
- [fetchReqeust setEntity:entifyDesc];
- //查询条件
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.age>40 && self.personId>10015"];
- [fetchReqeust setPredicate:predicate];
- //排序,按age降序排列
- NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
- [fetchReqeust setSortDescriptors:@[sortDesc]];
- //查询
- NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchReqeust error:nil];
- for (Person *p in persons) {
- NSLog(@"name=%@,age=%@,id=%@",p.name,p.age,p.personId);
- }
- }
参考资料:
Core Data Reference
API listing for the Core Data classes
http://developer.apple.com/documentation/Cocoa/Reference/CoreData_ObjC/index.html
NSPredicate Reference
API listing for NSPredicate
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSPredicate.html