我有一个核心数据配方对象,它包含一个成分对象的有序列表。
配料在UITableView中显示为列表。当用户取消编辑表视图时,我调用
rollback
在MOC上,它可以恢复一些成分(用户删除的任何成分)并删除其他成分(用户添加的任何成分)。我想动画的插入/删除,以便过渡是不是不和谐。
这比一开始看起来要难一点,特别是当你插入和移除同一个单元格时,UITableView会砍掉一个毛球。
有没有一些示例代码可以帮助我朝着正确的方向发展?现在,我有一个可笑的复杂设置使用NSMutableSets是不是很正常工作。
NSMutableArray *preIngredients = [NSMutableArray arrayWithArray:[recipe orderedIngredients]];
[self.recipe.managedObjectContext rollback];
NSMutableArray *postIngredients = [NSMutableArray arrayWithArray:[recipe orderedIngredients]];
NSMutableSet *beforeIngredients = [NSMutableSet setWithArray:preIngredients];
NSMutableSet *afterIngredients = [NSMutableSet setWithArray:postIngredients];
NSMutableSet *restoredIngredients = [NSMutableSet setWithSet:afterIngredients];
[restoredIngredients minusSet:beforeIngredients];
NSMutableSet *removedIngredients = [NSMutableSet setWithSet:beforeIngredients];
[removedIngredients minusSet:afterIngredients];
NSMutableSet *allIngredients = [NSMutableSet setWithSet:beforeIngredients];
[allIngredients unionSet:afterIngredients];
int whatToDo[[preIngredients count]];
for (int i = 0; i < [preIngredients count]; i++)
whatToDo[i] = 0;
for (Ingredient *ingredient in preIngredients) {
int row = [preIngredients indexOfObject:ingredient];
if ([removedIngredients containsObject:ingredient])
whatToDo[row]--;
if ([restoredIngredients containsObject:ingredient])
whatToDo[row]++;
}
for (int i = 0; i < [preIngredients count]; i++) {
if (whatToDo[i] < 0)
[rowsToRemove addObject:[NSIndexPath indexPathForRow:i inSection:0]];
else if (whatToDo[i] > 0)
[rowsToRestore addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
// Also remove the "add new ingredient" cell
NSIndexPath *insertNewCellIndexPath = [NSIndexPath indexPathForRow:[preIngredients count] inSection:0];
if ([rowsToRestore indexOfObjectIdenticalTo:insertNewCellIndexPath] == NSNotFound)
[rowsToRemove addObject:insertNewCellIndexPath];
else
[rowsToRestore removeObjectIdenticalTo:insertNewCellIndexPath];
[self.tableView insertRowsAtIndexPaths:rowsToRestore withRowAnimation:UITableViewRowAnimationTop];
[self.tableView deleteRowsAtIndexPaths:rowsToRemove withRowAnimation:UITableViewRowAnimationTop];