0

再会。使用函数时如何更改托管对象上下文中的上下文对象moveRowAtIndexPath:?这就是改变数组值的样子:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath{
     NSManagedObjectContext *context = [slef ManagedObjectContext];

     [tasks exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndexPath:toIndexPath.row]; //tasks is my array
     [tableview reloadData];
}

那么我怎样才能在其中交换对象context并将其保存在 Core Data 中呢?

4

1 回答 1

1

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

于 2013-05-28T13:15:06.307 回答