我正在研究如何使用 FRC 对 CoreData 中的单元格进行重新排序,我遇到了许多建议使用 order 属性并相应地更新它的帖子,下面是一个这样的代码
在插入新对象时,我必须设置显示顺序并根据
这是它的代码
- (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 个项目,我从中间删除任何一个项目,然后我必须重新计算 displayOrder,我认为这是不可行的。有没有其他方法可以执行此过程
问候兰吉特