从表视图中删除行

时间:2015-06-25 11:13:50

标签: ios uitableview core-data nsmanagedobject

我正在开发一个IOS应用程序。在表视图中删除tableview中的行和核心数据中的数据加载。单击删除按钮应用程序崩溃时。     原因是:Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (18) must be equal to the number of rows contained in that section before the update (18), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)...

_fetchedobj是一个从核心数据中获取数据的NSArray

//Code is
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _fetchedobj.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyReuseIdentifier";
    UITableViewCell *cell = [myTable dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier];
    }
    data = [_fetchedobj objectAtIndex:indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView beginUpdates];
        NSManagedObject *managedObject = [_fetchedobj objectAtIndex:indexPath.row];
        [self.managedObjectContext deleteObject:managedObject];
        [myTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [myTable endUpdates];
    }
}

3 个答案:

答案 0 :(得分:1)

您是否忘记从数据源阵列中删除此对象?

尝试重新填充_fetchedobj,因为您必须在删除后配置模型。有关更多详细信息,请阅读https://developer.apple.com/library/prerelease/ios/documentation/UserExperience/Conceptual/TableView_iPhone/ManageInsertDeleteRow/ManageInsertDeleteRow.html

试试这个

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView beginUpdates];
        NSManagedObject *managedObject = [_fetchedobj objectAtIndex:indexPath.row];
        [self.managedObjectContext deleteObject:managedObject];
        // insert this line to your code

        NSMutableArray *newA = [_fetchedobj mutableCopy ];
        [newA removeObjectAtIndex: indexPath.row];
        _fetchedobj = newA;

        [myTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [myTable endUpdates];
    }
}

答案 1 :(得分:0)

尝试使用此行删除表格视图行

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

答案 2 :(得分:0)

查看此链接,希望对您有帮助;)

http://www.ioscreator.com/tutorials/delete-rows-from-tableview