Get NSUserDefaults plist file from device

2019-04-08 20:24发布

When testing my app on the simulator, I like the ability to edit, or even trash the apps plist file (which contains the NSUserDefaults) from the iPhone Simulator folder. This proves useful when testing (e.g. your app stores a dictionary in there, but you change the model/keys that you use for this data, and therefore need to remove the dictionary stored).

Is it possible to access this file on device (for your own app), without jailbreak?

Thanks in advance

2条回答
Ridiculous、
2楼-- · 2019-04-08 20:36

The file is in Library/Preferences. The file is a binary plist with name <iOS application target identifier>.plist (look for the Identifier field in your app target settings), or list the directory contents:

NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];

You could also load clean defaults with a #ifdef macro based on some env variable:

#ifdef TESTING
    // use the code provided by tsakoyan below
#endif
查看更多
该账号已被封号
3楼-- · 2019-04-08 20:44

If you care only for the NSUserDefaults values, this should trash/restore to global defaults all its custom data

 NSDictionary *userDefDic = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
 NSArray *keys = [NSArray arrayWithArray:[userDefDic allKeys]];
 for (NSString *key in keys) {
     [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
 }
 [[NSUserDefaults standardUserDefaults] synchronize]; 
查看更多
登录 后发表回答