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()
这行得通。
但我想了解“ map ”以及如何使用它来映射部分。
tableView.insertSections(insertions.map { NSIndexSet(index: $0) }, withRowAnimation: .Automatic)
还有,
tableview.insertSections(insertions.map({ (index) -> NSIndexSet in
NSIndexSet(index: index)
}), withRowAnimation: .Automatic)
但是,两者都给我同样的错误
'map' produces '[T]', not the expected contextual result type 'NSIndexSet'
最佳答案
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)
但这似乎真的是在模糊代码而不是澄清代码。
关于ios - 如何使用 'map' 将 Realm 集合更改通知映射到 UITableview 部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37864017/