从NSUserDefaults字典iOs中删除所有键 [英] Delete all keys from a NSUserDefaults dictionary 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启用
您存储布尔值
,整数
, code>等等。我需要执行什么方法来删除所有的键,使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?
我在寻找例如:
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屋!