Jeff
Jeff

Reputation: 2699

NSUserDefaults: how to get only the keys I've set

All of the methods to get keys from NSUserDefaults return heaps of keys from domains other than the app itself (e.g., NSGlobalDomain). I just want the keys and values that my app has set. This is useful for debugging and verifying that there are no orphaned keys, etc.

I could ignore the keys that aren't mine (if I know all of them -- during development I may have set keys I'm no longer using), but there might be a collision of keys in other domains and I'll not see my app's value.

Other discussions suggest looking at the dictionary file associated with the app, but that's not very elegant.

How can I get only my app's keys form NSUserdefaults?

Upvotes: 2

Views: 541

Answers (2)

teacup
teacup

Reputation: 672

Marek's code updated to Swift 5:

guard let bundleIdentifier = Bundle.main.bundleIdentifier else { return }
let dict = UserDefaults.standard.persistentDomain(forName: bundleIdentifier)

Upvotes: 0

Marek H
Marek H

Reputation: 5566

Elegant approach

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary *dict = [defaults persistentDomainForName:bundleIdentifier];

File approach:

NSString *bundleIdentifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
NSString *path = [NSString stringWithFormat:@"~/Library/Preferences/%@.plist",bundleIdentifier];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[path stringByExpandingTildeInPath]];
NSArray *keys = [dict allKeys];

Tested with sandboxing.

Upvotes: 2

Related Questions