有没有一种方法可以获取NSUserDefaults中的所有值?

85
我想打印出我通过NSUserDefaults保存的所有值,而不需要提供特定的Key。
类似于使用for循环在数组中打印所有值。有没有一种方法可以这样做?

1
在你的应用程序领域还是系统领域? - awiebe
7
https://dev59.com/nHI-5IYBdhLWcg3wxrqQ - stosha
1
对于Swift,您可以使用此https://dev59.com/nHI-5IYBdhLWcg3wxrqQ#27534573 - footyapps27
4个回答

231

Objective C

所有的值:

NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues]);

所有的键:

NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);

所有的键和值:

NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

使用 for:

NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];

for(NSString* key in keys){
    // your code here
    NSLog(@"value: %@ forKey: %@",[[NSUserDefaults standardUserDefaults] valueForKey:key],key);
}

Swift

所有值:

print(UserDefaults.standard.dictionaryRepresentation().values)

所有的键:

print(UserDefaults.standard.dictionaryRepresentation().keys)

所有键和值:

print(UserDefaults.standard.dictionaryRepresentation())

1
Swift 3 所有的值:print(UserDefaults.standard.dictionaryRepresentation().values) 所有的键: print(UserDefaults.standard.dictionaryRepresentation().keys) - davidrynn

6

您可以使用:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *defaultAsDic = [defaults dictionaryRepresentation];
NSArray *keyArr = [defaultAsDic allKeys];
for (NSString *key in keyArr)
{
     NSLog(@"key [%@] => Value [%@]",key,[defaultAsDic valueForKey:key]);
}

相当易懂 - Soorej Babu

5

仅打印键

NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);

键和值

NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

4

您可以使用以下代码记录应用程序中所有可用的内容:

NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接