NSUserDefaults:如何只获取我设置的键

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

从 NSUserDefaults return 从应用程序本身以外的域(例如 NSGlobalDomain)获取密钥的所有方法。我只想要我的应用设置的键和值。这对于调试和验证没有孤立键等很有用

我可以忽略不属于我的密钥(如果我知道所有密钥——在开发过程中我可能设置了不再使用的密钥),但其他域中的密钥可能会发生冲突而且我不会看到我的应用程序的价值。

其他讨论建议查看与该应用关联的字典 文件,但这不是很优雅。

我怎样才能只从 NSUserdefaults 获取我的应用程序的密钥?

优雅的做法

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

文件路径:

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

已通过沙盒测试。

代码更新为 Swift 5:

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