交换上下文对象,如tableview中的行

时间:2013-05-26 19:00:47

标签: ios tableview nsmanagedobjectcontext

美好的一天。 当我使用函数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中呢?

1 个答案:

答案 0 :(得分: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个任务具有相同的索引。