Get NSUserDefaults plist file from device

2019-04-08 20:45发布

问题:

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

回答1:

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


回答2:

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];