简体   繁体   English

nsuserdefault的键值设置如何删除?

[英]nsuserdefault has key-values set how to delete it?

I have already tried to delete all the key-values pair when the app starts and again when i check keys these keys are saved in NSUserDefault. 我已经尝试在应用程序启动时删除所有键值对,并在我检查键时再次删除这些键,并将它们保存在NSUserDefault中。 I have these preferences stored. 我存储了这些首选项。

NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
NSLog(@"all keys %@", keys);


keys (
    NSLanguages,
    AppleITunesStoreItemKinds,
    AppleLocale,
    AppleLanguages,
    NSInterfaceStyle
)

When I store new dynamic values to the NSUserDefaults, I want to select all the keys except these preferences. 当我将新的动态值存储到NSUserDefaults时,我想选择除这些首选项以外的所有键。

Please help me with this problem. 请帮我解决这个问题。

Thanks in advance 提前致谢

Don't do what you're trying to do. 不要做你想做的事。 Don't tamper with any of the keys added by Apple. 不要篡改Apple添加的任何键。 Keep your own set of keys (preferably with prefixes on the names) and edit only those. 保留自己的一组键(最好在名称上带有前缀),然后仅编辑它们。

Generally you shouldn't delete keys unless there is some specific requirement in your app to do so. 通常,除非您的应用有特定要求,否则您不应该删除密钥。 What you should do is to set default values for each of your keys when the app starts: 您应该做的是在应用启动时为每个键设置默认值:

[[NSUserDefaults standardUserDefaults] registerDefaults:@{... : ...}];

These defaults will be valid while the app is running but won't be saved. 这些默认设置在应用程序运行时有效,但不会保存。 If you set anything using any of the set...:forKey: methods and synchronize then they will overwrite the defaults and be saved. 如果使用任何set...:forKey:方法设置任何内容并进行synchronize则它们将覆盖默认值并保存。

Try this 尝试这个

- (NSDictionary *) dictionaryRepresentation . - (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: 然后,您可以使用它清除用户默认设置:

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

removeObjectForKey -- that should give you the ability to remove a preference. removeObjectForKey-应该可以删除首选项。

You can remove everything in NSUserDefaults associated with your app by calling this. 您可以通过调用此操作来删除与应用程序关联的NSUserDefaults中的所有内容。

// remove entire user defaults
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize]; // not sure if needed, but never hurts

This should give you a clean slate for saving information to user defaults. 这样可以使您将信息保存到用户默认设置中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM