Roman
Roman

Reputation: 25

realm. remove objects from ListBase

I have different realm models. They have List properties. I want to make universal way for removing objects from List properties. So I did the following:

if let list = self[property.name] as? ListBase {
    list._rlmArray.removeAllObjects()
}

but this just clear list property, without deleting objects from realm. The only way I've found is:

if let list = self[property.name] as? ListBase {

    while list.count > 0 {
        let object = list._rlmArray.firstObject()
        let any = object as Any

        if let theObject = any as? Object {
            realm.delete(theObject)
        }
    }
}

Code above works and doesn't generate any warning. But it looks ugly.

Upvotes: 0

Views: 939

Answers (2)

Syed Faizan Ahmed
Syed Faizan Ahmed

Reputation: 544

When Realm removed ListBase the following solution worked for me. Use RLMSwiftCollectionBase instead of ListBase.

Original Source: https://github.com/caiyue1993/IceCream/pull/256#issuecomment-1034336992

Upvotes: 0

kishikawa katsumi
kishikawa katsumi

Reputation: 10573

You can use dynamicList(_ propertyName: String) to retrieve List property by name instead subscript.

if property.type == .array {
    try! realm?.write {
        realm?.delete(dynamicList(property.name))
    }
}

Upvotes: 0

Related Questions