Why can't I get the index of a filtered realm List?

泄露秘密 提交于 2020-01-06 06:56:28

问题


I'm trying to find the index of an item in a List<> object after the item has been appended to it, so that I can insert into a tableview.

The tableview is sectioned with .filters so I have to apply the filter before looking for the indexPath. However, the filter appears to break the indexOf functionality.

I noticed that the function .map has the same effect.

import UIKit
import RealmSwift

class Model: Object {
    @objc dynamic var title: String = ""
    let items = List<Model>()
}

class ViewController: UIViewController {

    var models: Results<Model>?
    var parentModel: Model?
    var items = List<Model>()
    let realm = try! Realm()

    override func viewDidLoad() {
        super.viewDidLoad()

        if !UserDefaults.standard.bool(forKey: "IsNotFirstTime") {
            populateRealm()
            UserDefaults.standard.set(true, forKey: "IsNotFirstTime")
        }

        models = realm.objects(Model.self)

        parentModel = models!.first
        items = parentModel!.items

        let child = Model()
        child.title = "Child"

        try! realm.write {
            parentModel!.items.append(child)
        }

        print(items.index(of: child)) // prints correct value
        print(items.filter({ $0.title == "Child" }).index(of: child)) // prints nil
    }

    func populateRealm() {
        let parent = Model()
        parent.title = "Parent"
        try! realm.write {
            realm.add(parent)
        }
    }
}

The first print finds the object, but the second print doesn't, despite the mapping having no overall effect.

The strange thing is that the object IS in the filtered list, doing:

print(items.filter({ $0.title == "Child" }).first

Returns the object, so it is there.

Edit

On further inspection, it looks like it's not the filter but the conversion of array type that breaks the functionality, converting to array without a filter does the same thing.

print(Array(items).index(of: child)) // prints nil

回答1:


When you want to use mapping you should add an attributes to map your objects according to it for example

    print(items.map({ $0.id }).index(of: child.id))

if you use it on this way it will return what you expected




回答2:


I figured out the solution. The filter syntax I used .filter({ $0.title == "Child" }) isn't the Realm filter, and converts the List to a LazyFilterCollection<List<Model>>, which doesn't seem to be compatible with searching for the index of a realm object.

The fix was to use the format .filter("title == %@", "Child"), which returns a realm Results object.



来源:https://stackoverflow.com/questions/50189689/why-cant-i-get-the-index-of-a-filtered-realm-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!