Skip to content

Instantly share code, notes, and snippets.

@danurna
Last active September 26, 2017 07:29
Show Gist options
  • Save danurna/2207f1c480e2cee85fcd3491cd9d3707 to your computer and use it in GitHub Desktop.
Save danurna/2207f1c480e2cee85fcd3491cd9d3707 to your computer and use it in GitHub Desktop.
Cascade Delete Realm Swift
import Foundation
import Realm
import RealmSwift
public extension Realm {
func cascadeDelete(_ entity: RLMObjectBase) {
guard let entity = entity as? Object else { return }
entity.objectSchema.properties.forEach { property in
if let value = entity.value(forKey: property.name) {
if let entity = value as? RLMObjectBase {
cascadeDelete(entity)
} else if let list = value as? RealmSwift.ListBase {
while let item = list._rlmArray.firstObject() {
cascadeDelete(item)
}
}
}
}
if !entity.isInvalidated {
self.delete(entity)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment