#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