1、查询对象,添加到数据源中
// 1.
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
request.sortDescriptors = @[sort];
// 执行查询请求
NSError *error = nil;
NSArray *result = [self.myDelegate.persistentContainer.viewContext executeFetchRequest:request error:&error];
[self.dataSource addObjectsFromArray:result];
2、添加对象
- (IBAction)insertModel:(UIBarButtonItem *)sender {
// 创建实体描述对象
NSEntityDescription *description = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:_myDelegate.persistentContainer.viewContext];
// 创建实体模型
Person *person = [[Person alloc] initWithEntity:description insertIntoManagedObjectContext:_myDelegate.persistentContainer.viewContext];
person.name = @"张三";
person.age = arc4random() % 100 + 1;
person.sex = @"女";
// 插入数据源数组
[self.dataSource addObject:person];
// 刷新
NSIndexPath *index = [NSIndexPath indexPathForRow:_dataSource.count - 1 inSection:0];
[self.myTableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
// 保存在数据管理器
[_myDelegate saveContext];
}
3.删除对象
Person *person = self.dataSource[indexPath.row];
[_myDelegate.persistentContainer.viewContext deleteObject:person];
[_myDelegate saveContext];
[self.dataSource removeObject:person];
[self.myTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
4.修改对象
Person *person = self.dataSource[indexPath.row];
person.name = @"李四";
[self.myTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.myDelegate saveContext];
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。