Search code examples
swiftfilterrealm

Realm filter not always finding data?


I have a Swift app that uses Realm as its database. In the app, I have a couple of models defined like this:

class Child: Object {
    @objc dynamic var id: Int = generateChildId()
    //other properties removed
}

class Parent: Object {
    @objc dynamic var id: Int = generateParentId()
    let children = List<Child>()
    //other properties removed
}

Elsewhere in my app, I have a method that deletes a Child object like this:

static func deleteChild(parentId: Int, childId: Int) {
    do {
        let realm = try Realm()
        realm.refresh()
        guard let parent = realm.objects(Parent.self).filter("id == %@", parentId).first else {
            print("Parent with ID: \(parentId) was not found!")
            return
        }

        guard let child = parent.children.filter("id == %@", childId).first else {
            print("Child with ID: \(childId) was not found!")
            print("This parent object has \(parent.children.count) children:")
            for child in parent.children {
               print("child ID: \(child.id)")
            }
            return
        }

        realm.delete(child)
    } catch {
        log.error(error)
    }
}

The Child objects are displayed in a UITableView. When I attempt to delete a Child object, I print out the ID to the Xcode console and then I call the deleteChild(parentId:childId) method above. Most of the time, this works as expected. But sometimes, the code that filters the Child objects by ID fails to find the matching object and prints "Child with ID: X was not found!" to the console. When this happens, I iterate through the .children property on the Parent object and print out all of the Child objects. The thing that's really confusing me is that when I do this, the Child object that I tried to find and delete appears to be there. For example:

Child with ID: 1559835636225 was not found!

This parent object has 5 children:
child ID: 1559835626285
child ID: 1559835628608
child ID: 1559835636225
child ID: 1559835643522
child ID: 1559835653041

Any idea what I'm doing wrong here?

---UPDATE---

My original post contained incorrect property names in the predicates (parentId and childId instead of just id). In my actual code, which I attempted to sanitize before posting, the property names are correctly specified as just "id". Sorry for the confusion.


Solution

  • As it turns out, this was a bug in Realm and has been addressed since 3.17.1.