CoreData使用方法

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];

你可能感兴趣的:(CoreData使用方法)