ios - 如何使用tableview删除核心数据中的数据

标签 ios objective-c uitableview core-data

我找不到如何从我的 TableView 中删除核心数据实体实例。

这就是我使用核心数据中的信息更新 TableView 的方式:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    Datos * record = [self.fetchedRecordsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ ",record.punto];

    UIImage* image = [UIImage imageWithData:record.imagen];
    cell.imageView.image = image;

    return cell; 
}

我正在尝试使用以下函数删除实体实例,但它不起作用:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{  
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

最佳答案

好吧,我不确定你从 CoreData 中获取数据的位置,但你需要调用那种代码片段,它不会在删除行时自行删除

- (void) deleteElement:(NSString*)elementId{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"YourTable" inManagedObjectContext:self.managedObjectContext]];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"id=%@",elementId]];

    NSError *error=nil;
    NSManagedObject *fetchedElement = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] lastObject];

    [self.managedObjectContext deleteObject:fetchedElement];

    if (![self.managedObjectContext save:&error]) {
        NSLog(@"problem deleting item in coredata : %@",[error localizedDescription]);
    }
}

您的代码应如下所示:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

     [self deleteElement:idOfElementToDelete];
}

这是错误:

'无效更新:第 0 节中的行数无效。更新 (2) 后现有节中包含的行数必须等于更新 (2) 前该节中包含的行数,加上或减去从该部分插入或删除的行数(0 插入,1 删除),加上或减去移入或移出该部分的行数(0 移入,0 移出)。'

关于ios - 如何使用tableview删除核心数据中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22355495/

相关文章:

iphone - presentModalViewController 和 presentViewController 的区别?

ios - 如何更改 Storyboard中的 "initwithNibName"?

ios - 如何返回多个 JSON 结果

ios - NSError 可以重用吗?

ios - 多个 CALayer 蒙版导致性能问题

ios - 无法在 iOS 中将 XMPPFramework 连接到 Openfire 服务器

ios - UITableViewCell,设置带有多个标签的动态高度

ios - 如何根据另一个单元格的值激活 uitableview 中的一个单元格?

ios - 查看层次结构约束错误

ios - UIView不圆角,UITableView单元格回收