FRC を使用して CoreData のセルを並べ替える方法に取り組んでいます。順序属性を使用し、それに応じてこれを更新することを提案する多くの投稿に出くわしました。そのようなコードの 1 つを以下に示します。
新しいオブジェクトを挿入するときに、表示順序を設定し、それに応じてインクリメントする必要があります
これがそのコードです
- (void)insertNewObject
{
Test *test = [NSEntityDescription insertNewObjectForEntityForName:@"Test" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *lastObject = [self.controller.fetchedObjects lastObject];
float lastObjectDisplayOrder = [[lastObject valueForKey:@"displayOrder"] floatValue];
[test setValue:[NSNumber numberWithDouble:lastObjectDisplayOrder + 1.0] forKey:@"displayOrder"];
}
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath;
{
NSMutableArray *things = [[fetchedResultsController fetchedObjects] mutableCopy];
// Grab the item we're moving.
NSManagedObject *thing = [[self fetchedResultsController] objectAtIndexPath:sourceIndexPath];
// Remove the object we're moving from the array.
[things removeObject:thing];
// Now re-insert it at the destination.
[things insertObject:thing atIndex:[destinationIndexPath row]];
// All of the objects are now in their correct order. Update each
// object's displayOrder field by iterating through the array.
int i = 0;
for (NSManagedObject *mo in things)
{
[mo setValue:[NSNumber numberWithInt:i++] forKey:@"displayOrder"];
}
[things release], things = nil;
// [managedObjectContext save:nil];
NSError *error = nil;
if (![managedObjectContext save:&error])
{
NSString *msg = @"An error occurred when attempting to save your user profile changes.\nThe application needs to quit.";
NSString *details = [NSString stringWithFormat:@"%@ %s: %@", [self class], _cmd, [error userInfo]];
NSLog(@"%@\n\nDetails: %@", msg, details);
}
// re-do the fetch so that the underlying cache of objects will be sorted
// correctly
if (![fetchedResultsController performFetch:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
しかし、100 個のアイテムがあり、途中から 1 つのアイテムを削除すると、displayOrder を再計算する必要がありますが、これは実現不可能だと思います。このプロセスを実行する別の方法はありますか
よろしくランジット