我找不到如何从我的 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/