最近在研究iOS的数据存取,就简单的总结一下。
CoreData
1.是什么
Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。
2.有什么用
简单的说就是能将OC的对象和数据相互转化,利用Core Data框架,可以轻松地将数据库里面的2条记录转换成2个OC对象,也可以轻松地将2个OC对象保存到数据库中,变成2条表记录,而且不用写一条SQL语句。
3.怎么用
![](https://img.haomeiwen.com/i234048/549f52318112e1bb.png)
![](https://img.haomeiwen.com/i234048/f4ebc1b18d90ad97.png)
新建一个实体Entity,命名为Student,添加两个属性。
![](https://img.haomeiwen.com/i234048/d62b922e3f9fcb38.png)
新建实体Teacher,一个属性name。建立和Student实体的关系(Inverse填Student后,Student的Inverse属性也会自动补上)。
下面就是见证奇迹的时刻了,创建NSManagedObject,即利用Core Data取出的实体都是NSManagedObject类型的,能够利用键-值对来存取数据。
![](https://img.haomeiwen.com/i234048/fe5ca8ec9c5f63e5.png)
![](https://img.haomeiwen.com/i234048/d28da2be6a2e6d6e.png)
![](https://img.haomeiwen.com/i234048/1fbdc8fc35715e46.png)
你会发现Teacher和Student类都自动创建了,现在就能随意使用了。
那么问题来了,这样就完了吗?
当然没有!说到数据库和数据存取就离不开,增、删、改、查。
搭建上下文环境
当然这一步一般都在AppDelegate里搭建好了,如果够懒得话,就直接调用。
AppDelegate*app = [UIApplicationsharedApplication].delegate;
NSManagedObjectContext*context = app.managedObjectContext;
这种方式创建的sqlite数据库名 默认为 工程名.sqlite 但有要求的话,也可自行修改。
增
Student *p =[NSEntityDescription insertNewObjectForEntityForName:
@"Student"inManagedObjectContext:context];
p.name=@"李四";
p.no=@11;
Teacher *teacher = [NSEntityDescription insertNewObjectForEntityForName:
@"Teacher"inManagedObjectContext:context];
teacher.name=@"李老师";
p.teacher = teacher;
//保存设置 把内存中的数据同步到数据库文件当中
[app saveContext];
删
NSFetchRequest*request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
NSArray*persons = [context executeFetchRequest:request error:nil];
for(Person*p in persons) {
[context deleteObject:p];
[app saveContext];
}
改
NSFetchRequest*request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
NSArray*persons = [context executeFetchRequest:request error:nil];
for(Person*p in persons) {
if([p.name isEqualToString:@"李四"])
{
p.name=@"王五";
[app saveContext];
}
}
查
//创建查询请求
NSFetchRequest* request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
NSArray*persons = [context executeFetchRequest:request error:nil];
for(Person *p in persons) {
NSLog(@"%@ %@",p.name,p.no);
NSLog(@" %@",p.teacher.name);
}
Tips
写完感觉有点乱,记录的较零碎,研究的也较浅,继续学习!
网友评论