我有一个 Collection View ,您可以在其中选择要删除的多个单元格。这意味着如果删除了多个单元格,那么 Realm 中也应该删除多个对象 - 每个单元格 1 个对象。
我有一个函数,它接受一个 Int
数组,该数组将从 Collection View 的选定 indexPaths 中填充。
问题是我不确定如何同时做这两件事
1)删除Realm和
中的对象
2) 更新 List
且没有删除的对象
我的代码是:
我得到的索引路径是这样的:
让 indexPaths = collectionView.indexPathsForSelectedItems
这是我的函数,用于获取 indexPaths、更新 List
并删除 Realm 中的对象。它目前不工作,因为对象没有被删除。我注意到 removeAll
不会删除任何内容。
func removeVideos(at indexes: [Int]) {
let newVideos = List<Video>()
for (index, video) in favorite!.videos.enumerated() {
if !indexes.contains(index) {
newVideos.append(video)
}
}
let realm = try! Realm()
try! realm.write {
favorite!.videos.removeAll()
newVideos.forEach { newVideo in
favorite!.videos.append(newVideo)
}
}
}
我这样调用该函数:
removeVideos(at: indexPaths.map { $0.item })
有什么想法吗?
最佳答案
List.removeAll()
不会从 Realm 中删除对象。它只是将它们从 List
对象中移除,删除它们与其父对象(在本例中为 favorite
对象)的关系。删除对象及其父 List
对象是一种称为“级联删除”和 it's still being discussed 的功能。在 Realm GitHub 上。
如果您真的想删除它们,只需调用realm.delete(favorite!.videos)
。这将从 Realm 中删除它们并自动清除 List
属性。
尽管如此,您可能需要谨慎实现。一旦从 Realm 中删除了一个 Object
,任何对它的现有引用都不能重新添加回 Realm。只删除 newVideo
对象本身而不是清除整个 List
可能是合适的。
func removeVideos(at indexes: [Int]) {
let newVideos = [Video]()
for (index, video) in favorite!.videos.enumerated() {
if !indexes.contains(index) {
newVideos.append(video)
}
}
let realm = try! Realm()
try! realm.write {
realm.delete(newVideos)
}
}
只要您在 Collection View 上设置了 Realm 通知 block ,就可以将它们从您的 UI 中删除。
关于ios - 从 Realm 中的列表中删除对象 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42912417/