Created
October 12, 2017 09:25
-
-
Save bagpack/14d617659a1d359e713aa30a21767496 to your computer and use it in GitHub Desktop.
truncate all tables in RealmSwift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RealmSwift | |
extension Realm { | |
static func truncateAll(`in` realm: Realm) { | |
for objectScheme in realm.schema.objectSchema { | |
if let clazz = Realm.clazz(fromClassName: objectScheme.className) { | |
try! clazz.deleteAll(in: realm) | |
} | |
} | |
} | |
static func clazz(fromClassName: String) -> Object.Type? { | |
// very fragile... | |
let object = String(reflecting: AppDelegate.self) | |
let namespace = object.components(separatedBy: ".").first! | |
let clazz: AnyClass = NSClassFromString("\(namespace).\(fromClassName)")! | |
return clazz as? Object.Type | |
} | |
} | |
extension Object { | |
static func deleteAll(`in` realm: Realm) throws { | |
let allObjects = realm.objects(self) | |
try realm.write { | |
realm.delete(allObjects) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment