继上一篇文章中介绍的插入数据,在插入数据代码的基础上,直接声明一个全局属性,引用添加的那一条person数据,来演示删除和更新数据的操作
@property (nonatomic,strong) Person *currentPerson;
插入数据:
// 通过数据模型子类
- (void)insertDataWithSubclass{
// 设置实体 entityForName (相当于表名)
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
// 创建并且插入的数据
Person *person = [[Person alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.appDelegate.managedObjectContext];
// 直接使用这条数据来演示删除操作
self.currentPerson = person;
// 设置数据
person.name = @"laozhang";
person.age = @30;
person.height = @158.2;
// 保存上下文
[self.appDelegate saveContext];
}
删除数据:
- (void)deleteData{
// 删除数据
[self.appDelegate.managedObjectContext deleteObject:self.currentPerson];
// 保存上下文
[self.appDelegate saveContext];
}
更新数据:
// 更新数据
- (void)updateData{
// 更新字段 (以更新name为例,和普通对象赋值属性一样)
self.currentPerson.name = @"lisi";
// 保存上下文
[self.appDelegate saveContext];
}
这样就通过面向对象的方式简单的实现了删除和更新的操作,不再需要使用SQL语句了