Is there a way to get all values in NSUserDefaults?

Alik Rokar picture Alik Rokar · Jul 8, 2013 · Viewed 43.3k times · Source

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?

Answer

Anton picture Anton · Jul 8, 2013

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