如何删除REALM数据库

时间:2016-08-10 10:01:16

标签: swift realm

我想从iOS应用程序注销时删除我的REALM数据库,所以我尝试了这个:

let realm = try! Realm()
try! realm.write {
    realm.deleteAll()
}
autoreleasepool {
    let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
    let realmURLs = [
        realmURL,
        realmURL.URLByAppendingPathExtension("lock"),
        realmURL.URLByAppendingPathExtension("log_a"),
        realmURL.URLByAppendingPathExtension("log_b"),
        realmURL.URLByAppendingPathExtension("note")
    ]
    let manager = NSFileManager.defaultManager()
    for URL in realmURLs {
        do {
            try manager.removeItemAtURL(URL)
            Log.warning("Removed file at path: \(URL)")
        } catch {
            Log.error("Failed to remove file at path: \(URL)")
        }
    }
}

然后,如果我尝试在不重新启动应用程序的情况下执行此操作,则会崩溃:

do
{
    try realm.write() { realm.create(UserDB.self, value: currentUser) }
} catch {
    Log.error("Unable to record the user to DB")
//TODO: Handle this situation
}

崩溃: Primary key can't be changed after an object is inserted.

更新:
尚未删除REALM文件log_alog_b 如果我在读取数据库并删除它之间执行realm.add,它只会崩溃,否则没问题。

一旦删除,我将重写一个新的数据库,主键将是用户的ID,这就是它崩溃的原因。但是,因为我的代码应该重置数据库,它会如何崩溃?

0 个答案:

没有答案