开发者

Why does reordering my tableView mess up my data?

开发者 https://www.devze.com 2023-02-28 23:14 出处:网络
I have two different table views in which I use the exact same code in tableView:MoveRowAtIndexPath:ToIndexPath: to support user reordering of the row开发者_开发问答s. One of these tableViews works pe

I have two different table views in which I use the exact same code in tableView:MoveRowAtIndexPath:ToIndexPath: to support user reordering of the row开发者_开发问答s. One of these tableViews works perfectly. The other one, however, gets confused and starts displaying the same subview no matter which row is selected - i.e. its row indexing seems to have got messed up.

I've temporarily fixed this by adding a [tableView reloadData] at the end of theMoveRowAtIndexPath method, but I don't understand why it wasn't working in the first place - especially since another view with the exact same code works perfectly. Obviously, there must be another method in this view controller which is messing it up, but I don't know where to look.

Here is the code that is the same in both:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {  
    userDrivenDataModelChange = YES;

    NSMutableArray *things = [[fetchedResultsController fetchedObjects] mutableCopy];   
    NSManagedObject *thing = [[self fetchedResultsController] objectAtIndexPath:fromIndexPath];   
    [things removeObject:thing];
    [things insertObject:thing atIndex:[toIndexPath row]];

    int i = 0;
    for (NSManagedObject *mo in things)
    {
        [mo setValue:[NSNumber numberWithInt:i++] forKey:@"displayOrder"];
    }

    [things release], things = nil;

    [managedObjectContext save:nil];
    userDrivenDataModelChange = NO;
}

(For what it's worth, the one that works is the child view of the one that doesn't, and they are in a to-many Core Data relationship).


Use a different identifier for each tableviews in

  • (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier

If you use the same identifier string, they will pickup each other's cached cell objects and show inconsistent data.


I forgot that I was using a custom cell on the parent view, and that the user presses a UIButton within the cell, rather than the cell itself. The custom cell has its index path set as a property by tableView:cellForRowAtIndexPath:, which of course never gets called again after the table cells are moved. Hence, I had to add a [tableView reloadData] to make sure the cells get updated.

0

精彩评论

暂无评论...
验证码 换一张
取 消