coreData

2018-11-22  本文已影响0人  懿懿懿懿懿懿懿

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];
}

coreData添加新数据的一些方法



保存实体的方法



查取实体的一些办法

如果需要查询实体使用

删除实体的方法



修改实体对象的方法
上一篇 下一篇

猜你喜欢

热点阅读