0

I'm having a problem to update a tableview if the user inserts identical items.

I think this will be easier to understand with the code.

I have an array of items that are currently shown in a table. When the user adds or deletes some items, I'm comparing the original array with the array of items to add or delete.

This is the method that compares the two arrays:

-(BOOL)compareToArray:(NSArray*)array2 blockNewItem:(void (^)(id obj))blockAddItem blockDelItem:(void (^)(id obj))blockDelItem{
    BOOL equal = YES;
    NSMutableArray *array2Copy = [NSMutableArray arrayWithArray:array2];
    for ( id index in self ){
        if ( ![array2 containsObject:index] ){
            if ( blockDelItem != nil )
                blockDelItem( index );
            equal = NO;
        }else
            [array2Copy removeObject:index];
    }

    for ( id index in array2Copy ){
        if ( blockAddItem != nil )
            blockAddItem( index );
        equal = NO;
    }

    return equal;
}

This method is called from another class that makes the update on the tableview:

[oldFields compareToArray:newFields blockNewItem:^(CustomTableItem* obj) {
        [added addObject:[NSIndexPath indexPathForRow:[newFields indexOfObject:obj] inSection:0]];
    } blockDelItem:^(CustomTableItem* obj) {
        [removed addObject:[NSIndexPath indexPathForRow:[oldFields indexOfObject:obj] inSection:0]];
    }];


    [_tableView beginUpdates];

if ( removed.count > 0 ){
        [_tableView deleteRowsAtIndexPaths:removed withRowAnimation:UITableViewRowAnimationFade];
    }
    if ( added.count > 0 ){
        [_tableView insertRowsAtIndexPaths:added withRowAnimation:UITableViewRowAnimationAutomatic];
    }

    _arrayFields = newFields;
    [_tableView endUpdates];

This works just fine if the user does not enter two identical items in the new array. In that case I'm getting an "invalid number of rows in section" error.

How to make it work in this case?

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
Aleph72
  • 877
  • 1
  • 13
  • 40
  • You've gotta work on your variable naming skills. Things like `array2` are meaningless, and using `index` to actually refer to items in the array is a poor choice, instead you should use `index` for the actual _indicies_ of the items in the array. – Stonz2 Mar 02 '20 at 17:32
  • I know, and I usually give different names to my variables, but this code is inherited. I'm trying to fix it. – Aleph72 Mar 03 '20 at 07:06
  • It looks like the answer here may help you https://stackoverflow.com/questions/21870680/invalid-update-invalid-number-of-rows-in-section-0/21870743 - basically update your data source first, before doing any row operations on the tableview. – BenW Mar 03 '20 at 15:03

0 Answers0