我想在iOS應用程序中重新排列UITableView。
收穫了不少的StackOverflow問題後,我用這個:最後一條解決重新排序UITableView支持核心數據拼圖
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
self.userDrivenDataModelChange = YES;
NSUInteger fromIndex = fromIndexPath.row;
NSUInteger toIndex = toIndexPath.row;
NSManagedObject *affectedObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:fromIndex];
[affectedObject setValue: [NSNumber numberWithInt:toIndex] forKey:@"priority"];
NSUInteger start, end;
int delta;
if (fromIndex < toIndex) {
// move was down, need to shift up
delta = -1;
start = fromIndex + 1;
end = toIndex;
} else { // fromIndex > toIndex
// move was up, need to shift down
delta = 1;
start = toIndex;
end = fromIndex - 1;
}
for (NSUInteger i = start; i <= end; i++) {
NSManagedObject *otherObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:i];
NSNumber *oldPriority = (NSNumber *)[otherObject valueForKey:@"priority"];
int tmp = [oldPriority intValue] + delta;
NSNumber *newPriority = [NSNumber numberWithInt:tmp];
[otherObject setValue: [NSNumber numberWithInt:[newPriority intValue]] forKey:@"priority"];
}
NSError *error = nil;
if (! [self.fetchedResultsController.managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
// Should I call something here?
self.userDrivenDataModelChange = NO;
}
發送保存消息上下文對象後,我應該怎麼稱呼?在獲取控制器或表視圖上的一些方法?因爲它不符合當前的形狀。
我應該首先發送保存到上下文對象嗎?
這似乎是它更新了各個單元的顯示數據,但沒有秩序,有沒有人設法讓這種方法要奏效? – 2012-05-01 20:57:37