ios 有没有办法获取 NSUserDefaults 中的所有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17522286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get all values in NSUserDefaults?
提问by Alik Rokar
I would like to print all values I saved via NSUserDefaults
without supplying a specific Key.
我想在NSUserDefaults
不提供特定密钥的情况下打印我保存的所有值。
Something like printing all values in an array using for
loop. Is there a way to do so?
类似于使用for
循环打印数组中的所有值。有没有办法这样做?
回答by Anton
Objective C
目标 C
all values:
所有值:
NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues]);
all keys:
所有键:
NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);
all keys and values:
所有键和值:
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
using for:
用于:
NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
for(NSString* key in keys){
// your code here
NSLog(@"value: %@ forKey: %@",[[NSUserDefaults standardUserDefaults] valueForKey:key],key);
}
Swift
迅速
all values:
所有值:
print(UserDefaults.standard.dictionaryRepresentation().values)
all keys:
所有键:
print(UserDefaults.standard.dictionaryRepresentation().keys)
all keys and values:
所有键和值:
print(UserDefaults.standard.dictionaryRepresentation())
回答by Midhun MP
You can use:
您可以使用:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *defaultAsDic = [defaults dictionaryRepresentation];
NSArray *keyArr = [defaultAsDic allKeys];
for (NSString *key in keyArr)
{
NSLog(@"key [%@] => Value [%@]",key,[defaultAsDic valueForKey:key]);
}
回答by yunas
Print only keys
仅打印密钥
NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);
Keys and Values
键和值
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
回答by Wain
You can log all of the contents available to your app using:
您可以使用以下方式记录您的应用程序可用的所有内容:
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);