Get NSUserDefaults plist file from device
Asked Answered
U

2

5

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

Underpay answered 26/7, 2011 at 10:42 Comment(3)
Can you not just delete the app from the simulator/device and then rebuild & run it again?Moran
That's a quick way to do it, but it will delete all the other application state-ful files as well, documents/temp folder etc.Soda
Wait will deleting the app from device remove the plist as well??Underpay
S
5

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
Sachsen answered 26/7, 2011 at 11:48 Comment(2)
In the docs it says resetStandardUserDefaults "Synchronizes any changes made to the shared user defaults object and releases it from memory"Soda
Thanks, I thought it would reset the defaults because of what I read in the Discussion section for that method "creates a new shared user defaults object with the standard search list", but that is intended to undo registerDefaults if I understood correctly. I +1'ed your answer below.Sachsen
S
3

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]; 
Soda answered 26/7, 2011 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.