Search code examples
swiftrealm

way to purge all but one object types (models) in a realm


I want to realm.delete() all but one model in my realm. Is there any way to do this without listing all of them?
Maybe a way to loop through all the types currently existing in a realm?


Solution

  • You can access the types from your Realm configuration, filter them to exclude the one you want to keep than delete each object of each type that you don't want to keep.

    let typeToBeKept = MyObjectClass.self
    realm.configuration.objectTypes?.filter{$0 != typeToBeKept}.forEach{ type in
        try! realm.write {
            realm.delete(realm.objects(type.self))
        }
    }