【问题标题】:How to use 'map' to map realm collection change notifications to UITableview sections?如何使用“地图”将领域集合更改通知映射到 UITableview 部分?
【发布时间】:2016-06-16 15:56:32
【问题描述】:

Realm Collection Notifications 在使用 'map' 与 UITableView 行进行映射时可以正常工作。我如何通过将其映射到 UITableView 部分来实现相同的效果。

对于行,我遵循以下代码:

notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
  guard let tableView = self?.tableView else { return }
  switch changes {
  case .Initial:
    tableView.reloadData()
    break
  case .Update(_, let deletions, let insertions, let modifications):
    tableView.beginUpdates()
    tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) },
      withRowAnimation: .Automatic)
    tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) },
      withRowAnimation: .Automatic)
    tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) },
      withRowAnimation: .Automatic)
    tableView.endUpdates()
    break
  case .Error(let error):
    // An error occurred while opening the Realm file on the background worker thread
    fatalError("\(error)")
    break
  }
}

对于部分,我使用:

tableview.beginUpdates()
                    for insertIndex in insertions {
                        tableview.insertSections(NSIndexSet(index: insertIndex), withRowAnimation: .Automatic)
                    }
                    for deleteIndex in deletions {
                        tableview.deleteSections(NSIndexSet(index: deleteIndex), withRowAnimation: .Automatic)
                    }
                    for reloadIndex in modifications {
                        tableview.reloadSections(NSIndexSet(index: reloadIndex), withRowAnimation: .Automatic)
                    }
                    tableview.endUpdates()

这行得通。

但我想了解“地图”以及如何使用它来绘制部分地图。

 tableView.insertSections(insertions.map { NSIndexSet(index: $0) }, withRowAnimation: .Automatic)

还有,

tableview.insertSections(insertions.map({ (index) -> NSIndexSet in
                        NSIndexSet(index: index)
                    }), withRowAnimation: .Automatic)

但是,两者都给了我同样的错误

“map”产生“[T]”,而不是预期的上下文结果类型“NSIndexSet”

【问题讨论】:

    标签: ios swift uitableview realm


    【解决方案1】:

    map 通过将每个原始集合元素替换为同一元素的映射版本来返回一个新集合。换句话说:

    insertions.map { ...}
    

    返回一个数组,而tableView.insertSections 需要一个 NSIndexSet 参数。

    您将得到的最接近的是:

    for indexSet in insertions.map { NSIndexSet(index: $0) } {
        tableView.insertSections(indexSet, ...)
    }
    

    或者,您可以创建一个 NSIndexSet,它是使用 reduce 的各个元素的组合,类似于:

    tableView.insertSections(insertions.reduce(NSMutableIndexSet()) {
        $0.addIndex($1)
        return $0
    }, withRowAnimation: .Automatic)
    

    但这似乎真的是在模糊代码而不是澄清它。

    【讨论】:

    • 谢谢。现在我知道地图功能是什么了。
    猜你喜欢
    • 2011-07-12
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多