Question

I have an app that uses an NSFetchedResultsController to grab various results from a database and display them in a UITableViewCell. For artistic reasons, at all times I want alternating cells to be left and right oriented, much like a conversation in Messages.

I'm currently achieving this by using an integer called entryIndexPath, which is incremented and then used in an if statement inside cellForRowAtIndexPath to determine whether the cell should be left or right aligned based on whether that integer is odd or even.

My problem is that when scrolling back up the table, this left/right assignment can get confused, and a cell that has just scrolled off can be re-assigned when re-appearing from the top, since cellForRowAtIndexPath is being called, the counter is being incremented.

I need a sure-fire way to ensure that when a new set of results is gotten from the FRC, that the left/right values are assigned correctly and firmly. I know that I need to do this outside of cellForRowAtIndexPath, but I'm struggling to see where I should do it. Any ideas, or suggestions?

EDIT: I'd also point out that my managed objects don't currently have a Left/Right variable or anything like that, so creating one would be pretty awkward, re-creating lots and lots of data, etc. If there a means of doing it without that, that'd be ideal.

Was it helpful?

Solution

Make sure you set the cell type for each row type explicitly. I would also suggest this alternative method to get the sequence from the indexPath:

NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
NSUInteger position = [self.fetchedResultsController.fetchedObjects indexOfObject:object];
NSString *cellIdentifier = position % 2 ? @"RightCell" : @"LeftCell";
id cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top