Roman Roman - 1 month ago 22
Swift Question

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.

Answer

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))
    }
}
Comments