【问题标题】:Reordering UITableViewCells with Core Data TableView使用 Core Data TableView 重新排序 UITableViewCells
【发布时间】:2013-04-18 13:38:53
【问题描述】:

我有一个 UITableView 正在为用户处理核心数据 o 添加他们自己的单元格......但我希望他们能够按照他们想要的方式重新排序 TableViewCells......我现在使用代码但是每当重新排序,假设我去添加另一个单元格,它将返回常规状态...如果您迷路了,请看下面的图片...

下面是代码:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
   if (indexPath.row == 0) // Don't move the first row
       return NO;

   return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{

 id ob = [_devices objectAtIndex:destinationIndexPath.row];

        [_devices replaceObjectAtIndex:destinationIndexPath.row withObject:[_devices objectAtIndex:sourceIndexPath.row]];
        [_devices replaceObjectAtIndex:sourceIndexPath.row withObject:ob];
}

【问题讨论】:

    标签: objective-c xcode uitableview core-data


    【解决方案1】:

    您应该在您的实体上添加一个 order 属性,以便您的排序顺序是持久的。

    那么你的表格视图的数据源需要按那个顺序键排序。

    很可能您的_devices 数组正在使用您的核心数据获取请求的结果重新初始化,因此您对订单的修改会丢失。

    已更新以供评论

    假设您有一个名为 Device 的实体,它是 NSManagedObject 的子类,具有一个名为 order 的属性,您可以执行以下操作。

    NSSortDescriptor *orderSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES];
    [devicesFetchRequest setSortDescriptors:@[orderSortDescriptor]];
    

    然后,当您执行 fetch 请求并将结果捕获到您的 _devices 数组中时,它们将按 order 属性排序。

    然后在- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath 中,您将需要更新受影响实体的订单属性。

    如果您将设备从位置 5 移动到位置 2,那么您需要将位置 2-4 的实体更新 +1,并将移动的实体更新为 2。这对于大型数据集可能会很快变得低效,但对于小型数据集它应该表现良好。

    【讨论】:

    • 那么如何做到这一点呢? PS这是在那个.m文件的顶部
    • @property (strong) NSMutableArray *devices;
    • 已更新答案,希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多