あなたのTasks
オブジェクトを考えてみましょう。並べ替えに使用するフィールドを追加する必要があります。
中身Tasks.h
@interface Tasks : NSManagedObject
...
@property (nonatomic, retain) NSNumber * index; // also update your codedata model to add a numeric 'index' field to it (Integer 64 for instance)
@end
@dynamic index;
また、実装 ( )で合成します。
タスクを取得したい場所:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tasks" inManagedObjectContext:[self managedObjectContext]];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// set the sort descriptors to handle the sorting
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
self.tasks = [[[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy] autorelease];
[request release];
最後に、並べ替えを処理します。
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath{
NSManagedObjectContext *context = [slef ManagedObjectContext];
Tasks *tfrom = [tasks objectAtIndex:fromIndexPath.row];
Tasks *tto = [tasks objectAtIndex:toIndexPath.row];
tfrom.index = [NSNumber numberWithInteger:toIndexPath.row];
tto.index = [NSNumber numberWithInteger:fromIndexPath.row];
// preferably save the context, to make sure the new order will persist
[managedObjectContext save:nil]; // where managedObjectContext is your context
[tasks exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndexPath:toIndexPath.row]; //tasks is my array
[tableview reloadData];
}
Tasks
既存のオブジェクトが既にある場合index
は、2 つのタスクが同じインデックスを持たないように、それらにフィールドを設定する必要があります。