0

良い一日。function を使用するときに、管理対象オブジェクト コンテキスト内のコンテキスト オブジェクトを変更するにはどうすればよい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 に答える