从 NSUserDefaults 字典 iOS 中删除所有键

发布于 2024-11-25 18:19:34 字数 1043 浏览 1 评论 0原文

我使用 NSUserDefaults 字典来存储基本信息,例如高分等,以便当用户关闭应用程序时数据不会丢失。无论如何,我使用:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

存储数据。例如,如果我希望存储一个新的高分,那么我会这样做:

[prefs setInteger:1023 forKey:@"highScore"];
[prefs synchronize];  //this is needed in case the app is closed. 

稍后,如果我希望检索高分,我会这样做:

[prefs integerForKey:@"highScore"];

无论如何,重点是我存储了很多其他内容,因为 NSUserDefaults enable< /code> 你要存储 booleansintegersobjects 等。我必须执行什么方法才能删除所有键,以便 NSUserDefaults 变得像我第一次启动该应用程序?

我正在寻找类似的东西:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs deleteAllKeysAndObjectsInTheDictionary];

或者也许有一种方法可以获取所有键,我必须循环遍历每个对象,但我不知道如何删除它们。

编辑:

我已经尝试过:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[NSUserDefaults resetStandardUserDefaults];
[prefs synchronize];

并且我仍然能够检索高分......

I use the NSUserDefaults dictionary to store basic information such as high scores etc so that when the user closes the app data is not lost. Anyways I use:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

to store data. If I wish to store a new high score for example then I would do:

[prefs setInteger:1023 forKey:@"highScore"];
[prefs synchronize];  //this is needed in case the app is closed. 

and later if I wish to retrieve the high score I would do:

[prefs integerForKey:@"highScore"];

anyways the point is that I store a lot of other things because the NSUserDefaults enable you to store booleans, integers, objects etc. what method would I have to execute to delete all keys so that NSUserDefaults becomes like the fist time I launch the app?

I am looking for something like:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs deleteAllKeysAndObjectsInTheDictionary];

or maybe there is a way of getting all keys and I have to loop through each object but I don't know how to remove them.

EDIT:

I have tried :

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[NSUserDefaults resetStandardUserDefaults];
[prefs synchronize];

and I still am able to retrieve a high score....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

_失温 2024-12-02 18:19:34

如果您查看 NSUserDefaults 文档 你会看到一个方法- (NSDictionary *)dictionaryRepresentation。在标准用户默认值上使用此方法,您可以获得用户默认值中所有键的列表。然后您可以使用它来清除用户默认值:

- (void)resetDefaults {
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}

If you have a look at the NSUserDefaults documentation you will see a method - (NSDictionary *) dictionaryRepresentation. Using this method on the standard user defaults, you can get a list of all keys in the user defaults. You can then use this to clear the user defaults:

- (void)resetDefaults {
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}
不离久伴 2024-12-02 18:19:34

获得相同结果的最短方法,如 Alex Nichol 的最佳答案:

NSString *appDomain = NSBundle.mainBundle.bundleIdentifier;
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize];

Shortest way to do this with the same results like in Alex Nichol's top answer:

NSString *appDomain = NSBundle.mainBundle.bundleIdentifier;
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize];
故事和酒 2024-12-02 18:19:34

单线:

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:NSBundle.mainBundle.bundleIdentifier];

One-liner:

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:NSBundle.mainBundle.bundleIdentifier];
墨落画卷 2024-12-02 18:19:34

简单解决方案

目标 C:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

Swift 3.0 到 Swift 5.0:

if let appDomain = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: appDomain)
}

Simple Solution

Objective C:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

Swift 3.0 to Swift 5.0 :

if let appDomain = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: appDomain)
}
胡渣熟男 2024-12-02 18:19:34

斯威夫特版本:

if let bid = NSBundle.mainBundle().bundleIdentifier {
    NSUserDefaults.standardUserDefaults().removePersistentDomainForName(bid)
}   

Swift version:

if let bid = NSBundle.mainBundle().bundleIdentifier {
    NSUserDefaults.standardUserDefaults().removePersistentDomainForName(bid)
}   
在梵高的星空下 2024-12-02 18:19:34

+ (void)resetStandardUserDefaults 不会保留更改,它只是重置内存中的用户默认对象,以便下一个 synchronize 调用将从磁盘副本中读取,而不是用磁盘上的版本覆盖现有的内存值。

迭代键更好,但实际上有一个函数可以为您执行此操作: removePersistentDomainForName:

// you can usually get the domain via [[NSBundle mainBundle] bundleIdentifier]
[[NSUserDefaults standardUserDefaults]
 removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
// or use a string for any other settings domains you use
//[[NSUserDefaults standardUserDefaults]
// removePersistentDomainForName:@"com.mycompany.myappname"];
[[NSUserDefaults standardUserDefaults] synchronize];

synchronize操作结束时,用户默认值的磁盘和内存副本将不包含应用程序设置的任何值。

+ (void) resetStandardUserDefaults doesn't persist the changes, it simply resets the in-memory user defaults object so that the next synchronize call will read from the on-disk copy, instead of overwriting existing in-memory values with the on-disk versions.

Iterating over the keys is better, but there's actually a function that does this for you: removePersistentDomainForName:.

// you can usually get the domain via [[NSBundle mainBundle] bundleIdentifier]
[[NSUserDefaults standardUserDefaults]
 removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
// or use a string for any other settings domains you use
//[[NSUserDefaults standardUserDefaults]
// removePersistentDomainForName:@"com.mycompany.myappname"];
[[NSUserDefaults standardUserDefaults] synchronize];

At the end of the synchronize operation, both the disk and memory copies of user defaults will contain none of the values set by your application.

风尘浪孓 2024-12-02 18:19:34

Swift 中的 Oneliner:

Swift 3

NSUserDefaults.standardUserDefaults().removePersistentDomainForName(
NSBundle.mainBundle().bundleIdentifier!)

Swift 4

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

Oneliner in Swift:

Swift 3

NSUserDefaults.standardUserDefaults().removePersistentDomainForName(
NSBundle.mainBundle().bundleIdentifier!)

Swift 4

UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
策马西风 2024-12-02 18:19:34

对于那些想要在测试目标中执行此操作的人,请使用它(因为 removePersistentDomain 不适用于这种情况)

Swift 3:

for key in Array(UserDefaults.standard.dictionaryRepresentation().keys) {
     UserDefaults.standard.removeObject(forKey: key)
}

For those of you that want to do this in the test target, use this (as the removePersistentDomain does not work for that case)

Swift 3:

for key in Array(UserDefaults.standard.dictionaryRepresentation().keys) {
     UserDefaults.standard.removeObject(forKey: key)
}
星光不落少年眉 2024-12-02 18:19:34

对于 Swift 3:

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

For Swift 3:

let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)
[浮城] 2024-12-02 18:19:34

对于斯威夫特 3:

if let bundle = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundle)
}

For Swift 3:

if let bundle = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundle)
}
向日葵 2024-12-02 18:19:34

我发现将代码放在 UserDefaults 的扩展中是最方便的。

Swift 5

extension UserDefaults {
    static func clear() {
        guard let domain = Bundle.main.bundleIdentifier else { return }
        UserDefaults.standard.removePersistentDomain(forName: domain)
        UserDefaults.standard.synchronize()
    }
}

用法

UserDefaults.clear()

I found it the most handy to place the code in an extension on UserDefaults.

Swift 5

extension UserDefaults {
    static func clear() {
        guard let domain = Bundle.main.bundleIdentifier else { return }
        UserDefaults.standard.removePersistentDomain(forName: domain)
        UserDefaults.standard.synchronize()
    }
}

Usage

UserDefaults.clear()
仙女山的月亮 2024-12-02 18:19:34

斯威夫特
放在你的逻辑中

if let appDomain = Bundle.main.bundleIdentifier {
  UserDefaults.standard.removePersistentDomain(forName: appDomain)
}

Swift
place in your logic

if let appDomain = Bundle.main.bundleIdentifier {
  UserDefaults.standard.removePersistentDomain(forName: appDomain)
}
清泪尽 2024-12-02 18:19:34

迅速

func resetUserDefaults(){
  let userDefaults = NSUserDefaults.standardUserDefaults()
  let dict = userDefaults.dictionaryRepresentation() as NSDictionary
        
  for key in dict.allKeys {
    userDefaults.removeObjectForKey(key as! String)
  }
        
  userDefaults.synchronize()      
}

Swift

func resetUserDefaults(){
  let userDefaults = NSUserDefaults.standardUserDefaults()
  let dict = userDefaults.dictionaryRepresentation() as NSDictionary
        
  for key in dict.allKeys {
    userDefaults.removeObjectForKey(key as! String)
  }
        
  userDefaults.synchronize()      
}
梅窗月明清似水 2024-12-02 18:19:34

此方法不这样做吗:

+ (void)resetStandardUserDefaults

来自 NSUserDefaults 的文档:

重置StandardUserDefaults

同步对共享用户默认对象所做的任何更改
将其从内存中释放。

+ (void)resetStandardUserDefaults

讨论

随后调用 standardUserDefaults 会创建一个新的共享
用户默认对象具有标准搜索列表。

基于此,您可以执行以下操作:

[NSUserDefaults resetStandardUserDefaults];
[NSUserDefaults standardUserDefaults];

现在应该重置默认值。

Does this method not do that:

+ (void)resetStandardUserDefaults

From the documentation for NSUserDefaults:

resetStandardUserDefaults

Synchronizes any changes made to the shared user defaults object and
releases it from memory.

+ (void)resetStandardUserDefaults

Discussion

A subsequent invocation of standardUserDefaults creates a new shared
user defaults object with the standard search list.

Based on this, you can do:

[NSUserDefaults resetStandardUserDefaults];
[NSUserDefaults standardUserDefaults];

and now the defaults should be reset.

静若繁花 2024-12-02 18:19:34

Swift 3 或 4
我们甚至可以将描述的片段简化为这个现代表达:

func clearAll() {
    let settingsDictionary = userDefaults.dictionaryRepresentation()
    settingsDictionary.forEach { key, _ in userDefaults.removeObject(forKey: key) }
    userDefaults.synchronize()
}

Swift 3 or 4
We can even simplify described snippet into this modern expression:

func clearAll() {
    let settingsDictionary = userDefaults.dictionaryRepresentation()
    settingsDictionary.forEach { key, _ in userDefaults.removeObject(forKey: key) }
    userDefaults.synchronize()
}
无可置疑 2024-12-02 18:19:34

在 Swift 5.0 下面,单行代码就足够了。

UserDefaults.standard.dictionaryRepresentation().keys.forEach(defaults.removeObject(forKey:))

In Swift 5.0 below single line of code is enough.

UserDefaults.standard.dictionaryRepresentation().keys.forEach(defaults.removeObject(forKey:))
强辩 2024-12-02 18:19:34

快速删除所有 UserDefault 值(最新语法)

//remove UserDefaults
if let identifier = Bundle.main.bundleIdentifier {
  UserDefaults.standard.removePersistentDomain(forName: identifier)
  UserDefaults.standard.synchronize()
}

To remove all UserDefault value in swift (Latest syntax)

//remove UserDefaults
if let identifier = Bundle.main.bundleIdentifier {
  UserDefaults.standard.removePersistentDomain(forName: identifier)
  UserDefaults.standard.synchronize()
}
心凉 2024-12-02 18:19:34

我用这个:

UserDefaults.standard.removeAll()

I use this:

UserDefaults.standard.removeAll()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文