coreData数据库 是一种持久化,将数据给保存起来.
1.在创建项目的时候将coreData给勾选起来
2.找到创建coreData的东西,创建coreData
3.创建coreData的类,写coreData的方法
coreData的写法,增删获取
-(void)saveOneName:(Name *)name{
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
//描述实体,将实体的对象赋值给name;
Entity *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:app.persistentContainer.viewContext];
//将model类中的元素赋值给coreData中的元素
entity.name = name.name;
NSError *error = nil;
//执行保存的方法
BOOL isOK = [app.persistentContainer.viewContext save:&error];
//通过BOOL的方法进行判断是否添加实体成功
NSLog(@"%d",isOK);
}
-(NSArray *)getAllname{
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
//描述实体中的对象
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:app.persistentContainer.viewContext];
//抓取实体中的对象
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entity];
//将抓取到的元素赋值给数组中
NSArray *array = [app.persistentContainer.viewContext executeFetchRequest:request error:nil];
//返回数组的元素
return array;
}
-(void)deleteName:(id)name{
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
[app.persistentContainer.viewContext deleteObject:name];
[app.persistentContainer.viewContext save:nil];
}
-(void){
//刷新实体的办法
AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSError = nil;
[app.persistentContainer.viewContext save:&error];
}
![](https://img.haomeiwen.com/i13932455/24898458d7b2a66a.png)
coreData添加新数据的一些方法
![](https://img.haomeiwen.com/i13932455/314cb5c25c999fef.png)
保存实体的方法
![](https://img.haomeiwen.com/i13932455/e34f239c7d042ba7.png)
查取实体的一些办法
![](https://img.haomeiwen.com/i13932455/ede74db1dbca0c90.png)
如果需要查询实体使用
![](https://img.haomeiwen.com/i13932455/01c99f0e57a89710.png)
删除实体的方法
![](https://img.haomeiwen.com/i13932455/570df2f317ace02b.png)
修改实体对象的方法
![](https://img.haomeiwen.com/i13932455/c0156c969e7b04fa.png)
网友评论