Core Data:ios5以后出现的一个框架
可以将oc对象转化成数据,保存在sqlite中
Core Data使用步骤
1.创建模型文件
1-1新建文件找到Core Data里面的DataModel类型
2.添加实体
1-2点击新建的DataModel添加Attributes类型,设置Attribute和type
3.创建实体类
1-3新建文件找到NSManageObject类型类似模型,会自动生成对应的Core Data
4.生成上下文,关联模型文件生成数据库
4-1.上下文声明,关联时如果没有本地数据库,会自动生成
context = [[NSManagedObjectContext alloc]init];
4-2.
上下文关联数据库
持久化的一个存储对象
持久化存储调度起
持久化:就是把数据保存到一个文件里而不是保存到内存里
4-3.模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
4-4.保存到某一个目录告诉Core Data数据库的名字和路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
[ store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
context.persistentStoreCoordinator = store;
5.保存对象到数据库
5-1. Employee时我们前面创建的一个类
Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:context];
5-2.添加内容
emp.name = @"pp";
emp.height = @190;
emp.birthday = [NSDate date];
5-3.直接保存到数据库
NSError *error = nil;
[context save:&error];
6.从数据库获取对象
6-1.FetchRequest抓取请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
6-2.设置过滤条件
给个过滤条件:如查找pp
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"pp"];
6-3.放入request
request.predicate = pre;
6-4.设置排序,升序改为no是降序
NSSortDescriptor *heigisort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
request.sortDescriptors = @[heigisort];
6-5.执行请求
NSError *error = nil;
NSArray *emoloys = [context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"%@",error);
}
7.更新数据
7-1.更改pp的身高为2米
查找pp
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
7-2.设置过滤条件,给个过滤如查找pp
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"pp"];
7-3.放入request
request.predicate = pre;
7-4.执行请求
NSError *error = nil;
NSArray *emoloys = [context executeFetchRequest:request error:&error];
7-5.更新
for (Employee *e in emoloys) {
e.height = @200;
}
7-6.保存
[context save:nil];
8.删除数据
8-1.先查找,删除条件,删除pp
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
8-2.设置过滤条件,给个过滤如查找pp
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"pp"];
8-3.放入request
request.predicate = pre;
8-4.删除
8-5.执行请求
NSError *error = nil;
NSArray *emoloys = [context executeFetchRequest:request error:&error];
8-6.更新
for (Employee *e in emoloys) {
[context deleteObject:e];
}
8-7.保存
[context save:nil];