【问题标题】:Reordering Realm objects in a UITableView在 UITableView 中重新排序 Realm 对象
【发布时间】:2016-02-04 05:22:06
【问题描述】:

我有一组 RLMObject 模型对象,这些对象代表用户的登录帐户 可以在我的应用程序中管理。这些对象通过直接映射到UITableView 来公开 在应用程序中。

由于用户可以通过以下方式显式控制这些帐户对象的顺序 在表格视图中,模型对象具有一个名为orderedIndex 的属性,按顺序排列 跟踪对象的当前顺序。

@interface Account : RLMObject

@property NSString *name;
@property NSInteger orderedIndex;

@end

表格视图数据源通过RLMResults 属性访问这些帐户 父视图控制器的成员

self.accounts = [[Account allObjects] sortedResultsUsingProperty:@"orderedIndex" ascending:YES];

(感谢 Realm 对象是“实时”的,我无需手动重新加载 或重置此对象。)

当用户对表格视图的行重新排序时,所有的orderedIndex属性 需要更新这些 Realm 对象以匹配。

可能有很多不同的方法可以做到这一点,有些比其他的更复杂, 但是什么是最简单的呢?

【问题讨论】:

    标签: ios objective-c uitableview realm


    【解决方案1】:

    最初,我在确定哪些特定的 Realm 对象时试图对此保持聪明 受到此举的影响,只修改了他们的orderedIndex 值,但这变成了 有点复杂,并且在某些边缘情况下(通常涉及顶部和底部的对象), 会导致不可预测的行为。

    最终,我决定为了最简单(以稍微多一点的工作为代价),我会 只需将我的 self.accounts 对象的内容复制到一个可变数组,执行 在数组中移动操作,然后简单地重建每个对象的orderedIndex 从头开始。

    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(nonnull NSIndexPath *)sourceIndexPath toIndexPath:(nonnull NSIndexPath *)destinationIndexPath
    {   
       if (sourceIndexPath.row == destinationIndexPath.row) {
           return;
       }
    
       // Make a mutable copy of the accounts list
       NSMutableArray *array = [NSMutableArray array];
       for (Account *account in self.accounts) {
           [array addObject:account];
       }
    
       // Re-order this array as dictated by the table view
       Account *accountToMove = array[sourceIndexPath.row];
       [array removeObject:accountToMove];
       [array insertObject:accountToMove atIndex:destinationIndexPath.row];
    
       // Loop through all of the items and reset their index value
       [self.accounts.realm transactionWithBlock:^{
           NSInteger i = 0;
           for (Account *account in array) {
               account.orderedIndex = i++;
           }
       }];
    }
    

    最终完美运行。 :)

    【讨论】:

    • 未来您可以考虑的另一个想法是为您的订单属性使用浮点数或双精度数。要确定一条记录的新顺序,您只需平均它所在行的顺序,这意味着您只需更新数据库中的一条记录。
    【解决方案2】:

    解决这个问题的另一种方法是使用 Realm 的 List 数据结构。因此,您可以拥有一个 Realm 对象列表,并且重新排序列表中的元素与重新排序常规数组的方式完全相同。如果有兴趣,您可以查看以下链接以了解如何为 Swift 完成此操作。 :-)

    Incorrect UI update after reordering rows in UITableViewController

    【讨论】:

    • 您介意我问一下,您的List 数据结构是存储在Realm 中还是内存中?我刚刚实现了一个带有let items = List<Item>() 属性的Sorter 领域对象来存储我的Items 并保持它们的顺序,这很有效,但我想知道我是否需要完成所有这些工作,或者是否有更好的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多