从 NSUserDefaults 字典 iOS 中删除所有键 [英] Delete all keys from a NSUserDefaults dictionary iOS

查看:31
本文介绍了从 NSUserDefaults 字典 iOS 中删除所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 NSUserDefaults 字典来存储基本信息,例如高分等,以便在用户关闭应用程序时不会丢失数据.反正我用:

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"];

无论如何,关键是我存储了很多其他东西,因为 NSUserDefaults 使 你可以存储 booleansintegersobjects 等.我必须执行什么方法才能删除所有键,以便 NSUserDefaults 就像我第一次启动应用程序一样?

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.

我试过了:

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

而且我仍然能够检索到高分....

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

推荐答案

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

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];
}

这篇关于从 NSUserDefaults 字典 iOS 中删除所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆