CoreData的基本使用

来源:互联网 发布:移动联通电信网络频段 编辑:程序博客网 时间:2024/06/05 09:47

#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 {

    [superviewDidLoad];

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

    

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

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

    NSLog(@"%@", [NSPersistentContainerdefaultDirectoryURL]);

    

    [self.appdelegatepersistentContainer];

}


//插入数据

- (IBAction)clickInsertDataBtn:(id)sender {

    

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

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

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

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

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

    

    Person *person = [[Personalloc] initWithEntity:entityinsertIntoManagedObjectContext: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.appdelegatesaveContext];

    

    self.currentPerson = person;

}


//更新数据

- (IBAction)clickUpdateDataBtn:(id)sender {

    

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

    

    //更新数据

    self.currentPerson.name =@"wangwu";

    

    //保存数据

    [self.appdelegatesaveContext];

}



//删除数据

- (IBAction)clickDeleteDataBtn:(id)sender {

    //删除数据

    [self.appdelegate.persistentContainer.viewContextdeleteObject:self.currentPerson];

    //保存上下文

    [self.appdelegatesaveContext];

}


@end


原创粉丝点击