如何删除所有 UserDefaults 数据? - Swift

How to remove all UserDefaults data ? - Swift

我有这段代码可以从应用程序中删除所有 UserDefaults 数据:

let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)

print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)

但我从打印行得到了 10。不应该是0吗?

这个答案在 处找到,但以防万一它在 Swift.

func resetDefaults() {
    let defaults = UserDefaults.standard
    let dictionary = defaults.dictionaryRepresentation()
    dictionary.keys.forEach { key in
        defaults.removeObject(forKey: key)
    }
}

问题是您在清除 UserDefaults 内容后立即打印它们,但您没有手动同步它们。

let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)

这应该可以解决问题。

现在您通常不需要手动调用 synchronize,因为系统会定期自动同步 userDefaults,但如果您需要立即推送更改,则需要通过 synchronize 呼叫.

The documentation states this

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.