0

我已经尝试在应用程序启动时删除所有键值对,当我再次检查键时,这些键保存在 NSUserDefault 中。我存储了这些首选项。

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


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

当我将新的动态值存储到 NSUserDefaults 时,我想选择除这些首选项之外的所有键。

请帮我解决这个问题。

提前致谢

4

3 回答 3

2

Don't do what you're trying to do. Don't tamper with any of the keys added by 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.

于 2013-09-16T12:25:58.187 回答
2

尝试这个

- (NSDictionary *) dictionaryRepresentation. 在标准用户默认值上使用此方法,您可以获得用户默认值中所有键的列表。然后,您可以使用它来清除用户默认值:

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

removeObjectForKey - 这应该使您能够删除首选项。

于 2013-09-17T04:29:05.030 回答
0

NSUserDefaults您可以通过调用它来删除与您的应用程序关联的所有内容。

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

这应该为您提供一个干净的状态,用于将信息保存到用户默认值。

于 2013-09-16T12:41:59.623 回答