17
votes

Does anyone know of a quick way to dump the standardUserDefaults of NSUserDefaults via NSLog? This is what I have:

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

But it returns:

NSUserDefaults dump: <NSUserDefaults: 0x50b520>

...which is not quite what I'm looking for. I'd really like to have key-value pairs.

Any help or a point in the right direction would be greatly appreciated. Cheers!

6

6 Answers

36
votes
NSLog(@"NSUserDefaults dump: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
19
votes

Thanks to Don McCaughey, my business partner and friend, for fixing up my code for me and supply a concise answer. To share it with the rest of you here is a code snippet:

  NSDictionary *bundleInfo = [[NSBundle mainBundle] infoDictionary];
  NSString *bundleId = [bundleInfo objectForKey: @"CFBundleIdentifier"];

  NSUserDefaults *appUserDefaults = [[NSUserDefaults alloc] init];
  NSLog(@"Start dumping userDefaults for %@", bundleId);
  NSLog(@"userDefaults dump: %@", [appUserDefaults persistentDomainForName: bundleId]);
  NSLog(@"Finished dumping userDefaults for %@", bundleId);
  [appUserDefaults release];

As you can see, everyone who was answering the question was on the right track, but no code offered up was the solution - until Don's editing of our code in source control. Thanks All!

9
votes

Try:

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

dictionaryRepresentation returns an NSDictionary representation of the defaults.

8
votes
NSLog(@"%@ defaults = %@", [self class], 
  [[NSUserDefaults standardUserDefaults] 
   persistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]]);
6
votes

The shared NSUserDefaults is initialized with three search domains by default (you can add others too if you need to): app arguments, app preferences (what's stored in the app's plist), and localized system preferences. The last one is why you're seeing those unfamiliar Apple keys, but you don't really have to worry about "overwriting" them. If you use the same key name, it will just put that value in the app preferences domain. Your app's preferences is searched before the system preferences so you'll get the same value back, but it won't affect anything else.

If you really do want just your app's preferences though, you can remove the other search domains (the specific names you need is in the docs).

1
votes

Here is a handy class that you can use to dump all kinds of crap:

https://github.com/VTPG/CommonCode/blob/master/VTPG_Common.h

To use it, add the header to your "m"

#import "VTPG_Common.h"

then anywhere in your class call LOG_EXPR(foo):

NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
[userDefaults addSuiteNamed:@"com.apple.spaces"];
NSDictionary *foo = [userDefaults dictionaryForKey:@"SpacesDisplayConfiguration"];
LOG_EXPR(foo);