让我们考虑一下您的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 个任务具有相同的索引。