CoreData的基本使用

#import "ViewController.h"

#import "AppDelegate.h"

#import "Person+CoreDataClass.h"


@interface ViewController ()


@property (nonatomic, strong) AppDelegate *appdelegate;


@property (nonatomic, strong) Person *currentPerson;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    self.appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    //获取CoreData数据库的默认存储路径

    NSLog(@"%@", [NSPersistentContainer defaultDirectoryURL]);

    

    [self.appdelegate persistentContainer];

}


//插入数据

- (IBAction)clickInsertDataBtn:(id)sender {

    

    //1.创建实体描述对象 获取实体映射关系

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appdelegate.persistentContainer.viewContext];

    //CoreData数据必须封装到NSManagedObject类型的对象中

    //2.创建数据模型并且插入数据到上下文

//    NSManagedObject *person = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.appdelegate.persistentContainer.viewContext];

    

    Person *person = [[Person alloc] initWithEntity:entity insertIntoManagedObjectContext:self.appdelegate.persistentContainer.viewContext];

    

    //3.设置数据   CoreData会视图映射关系,在运行时给数据模型对象添加对应的成员变量

//    [person setValue:@"zhangsan" forKey:@"name"];

//    [person setValue:@22 forKey:@"age"];

//    [person setValue:@166 forKey:@"height"];

    

    //Xcode8.1开始,数据模型文件会自动生成数据模型的子类(生成路径在系统路径下),使用数据模型子类时,只需要Build一下,就可以引用和使用子类

    person.name = @"lisi";

    person.age = 20;

    person.height = 177;

    

    //4.保存上下文

    [self.appdelegate saveContext];

    

    self.currentPerson = person;

}


//更新数据

- (IBAction)clickUpdateDataBtn:(id)sender {

    

    //从数据库中获取数据模型

    

    //更新数据

    self.currentPerson.name = @"wangwu";

    

    //保存数据

    [self.appdelegate saveContext];

}



//删除数据

- (IBAction)clickDeleteDataBtn:(id)sender {

    //删除数据

    [self.appdelegate.persistentContainer.viewContext deleteObject:self.currentPerson];

    //保存上下文

    [self.appdelegate saveContext];

}


@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值