Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andr3a88/d4171d105503a754f908148bc40f76ab to your computer and use it in GitHub Desktop.
Save andr3a88/d4171d105503a754f908148bc40f76ab to your computer and use it in GitHub Desktop.
Realm+CascadingDeletions
import Foundation
import RealmSwift
protocol CascadingDeletable {
var cascadingDeletions: [AnyObject?] { get }
}
extension Realm {
func delete<T: AnyObject>(_ objects: List<T>, cascade: Bool = true) where T: CascadingDeletable {
delete(objects.toArray(), cascade: cascade)
}
func delete<T: AnyObject>(_ objects: Results<T>, cascade: Bool = true) where T: CascadingDeletable {
delete(objects.toArray(), cascade: cascade)
}
func delete<T: AnyObject>(_ objects: [T], cascade: Bool = true) where T: CascadingDeletable {
if !cascade {
delete(objects)
return
}
for object in objects {
delete(object, cascade: true)
}
}
func delete<T: AnyObject>(_ object: T, cascade: Bool = true) where T: CascadingDeletable {
if !cascade {
delete(object)
return
}
for child in object.cascadingDeletions {
if let cascadingChild = child as? T {
delete(cascadingChild, cascade: true)
continue
}
if let child = child as? Object {
delete(child)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment