使用Fetch Resulte Controller重新排序Coredata中的细胞



我正在研究如何使用frc重新排序小区,我遇到了许多帖子,这些帖子建议使用订单属性并相应地更新此,一个这样的代码在此处

插入新对象时,我必须设置显示顺序并根据

进行递增

这是它的代码

- (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(@"%@nnDetails: %@", 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个项目,我从中间删除任何一个项目,然后我必须重新计算显示器,我认为这是不可行的。是否有其他方法可以执行此过程

问候ranjit

您为什么认为您需要重新计算索引号?

这些项目是根据您应用的排序顺序排列的。

如果您提供了上升的排序订单,并且提供了一个数字,那么您将获得正确的分类。您不需要的是您订购项目的数字与数组中项目索引之间的直接通信。例如:如果您的订单号为

1 2 3 4

然后,当您获取它们并对其进行排序时,它们将以此顺序出现。但是,如果订单号不同,它们仍然以相同的顺序出现。

1 3 5 7

数字丢失并不重要,因为它们仅用于排序,而不是记录位置。

现在,让我们想象您根据索引有4个项目。

1 2 3 4

现在删除第二项

1 3 4

您的项目少1个,但它们的顺序仍然相同。说您在末尾添加一个项目:

1 3 4 5

现在想象您想在末尾移动项目处于第三位。这是您问自己另一个问题的地方:为什么订购索引必须是整数?如果使用浮子,您会发现很容易计算新索引作为前几个数字和之后的数字之间的中点。因此,在将项目末端移至第三位置之后,这就是订购索引的样子:

1.0 3.0 3.5 4.0

在第二个位置中添加数字怎么样。在这种情况下,中点很容易计算:

1.0 2.0 3.0 3.5 4.0

所以。使用订购索引没有错。它不需要是整数,因此,当您删除一个项目时,您不必再次计算所有索引。

现在,这些浮子很可能会变得杂乱地生长,但是您可以在应用程序的停机时间内定期进行重新计算,或者在用户期望设置的更新期间。

最新更新