简体   繁体   中英

iOS Invalid Row Update Exception

I'm making an SMS-style component of an iOS app. The messaging view is a UITableView . I want to add a new row to the table for both a sent message and an incoming message. The call to add a row for an incoming message comes through KVO via a dedicated serial thread. Similarly through KVO for send success, the call to add a row for a sent message comes from a different dedicated serial thread. If there is a call to add a row from an incoming message and another call to add a row for a sent message at near the exact same time, the app throws an exception for invalid rows:

'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (31) must be equal to the number of rows contained in that section before the update (29), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

Is this a thread safety issue? How can I fix it? Here is the relevant method called from the two different threads:

-(void)addRowToMessageTable {    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow: [_messageTable numberOfRowsInSection:0] inSection: 0];
        [_messageTable beginUpdates];
        [_messageTable insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [_messageTable endUpdates];
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _privateMessages.count;
}

Table view update method internally loads the table again so it again calls the delegate method . You are getting the exception because you have added the row to the table but you have not added that object to the _privateMessages array . Add same object to array so the count will be same before and after update .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM