Is there a way to get all values in NSUserDefaults? [duplicate]

∥☆過路亽.° 提交于 2020-05-24 20:06:12

问题


I would like to print all values I saved via NSUserDefaults without supplying a specific Key.

Something like printing all values in an array using for loop. Is there a way to do so?


回答1:


Objective 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())



回答2:


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]);
}



回答3:


Print only keys

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

Keys and Values

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



回答4:


You can log all of the contents available to your app using:

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


来源:https://stackoverflow.com/questions/17522286/is-there-a-way-to-get-all-values-in-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!