Ahmed
Ahmed

Reputation: 15069

Are NSUserDefaults tied to the bundle identifier?

I would like to know if the NSUserDefaults is tied to bundle identifier ?

For example, I have version 1.0 bundle identifier was com.something and this app saved some settings in the NSUserDefaults.standardDefaults

Now sometime later if an update comes and we are required to change bundle identifier for some reason, will the new version be able to access settings/preferences stored by previous version ?

The app is NOT published APP STORE BUT has package installer

Upvotes: 5

Views: 1769

Answers (2)

user557219
user557219

Reputation:

If you change the bundle identifier, you’ll have a different set of user defaults. You can still read the old defaults provided your application is not sandboxed. For example, if your old bundle identifier is com.company.aaa, you can use the following code to copy the old defaults to the new application+bundle identifier when your application starts:

// Read the old defaults from com.company.aaa
NSUserDefaults *oldDefaults = [NSUserDefaults new];
NSDictionary *oldDefaultsDict = [oldDefaults persistentDomainForName:@"com.company.aaa"];

// Store the old defaults in the standard user defaults
[[NSUserDefaults standardUserDefaults] setPersistentDomain:oldDefaultsDict forName:[[NSBundle mainBundle] bundleIdentifier]]];

You’ll probably want to store a defaults flag to indicate that you’ve imported the old defaults once in order to avoid rewriting them subsequently. For example:

NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
if (! [currentDefaults boolForKey:@"importedOldDefaultsFromAAA"]) {
    // Read the old defaults from com.company.aaa
    NSUserDefaults *oldDefaults = [NSUserDefaults new];
    NSDictionary *oldDefaultsDict = [oldDefaults persistentDomainForName:@"com.company.aaa"];

    // Store the old defaults in the standard user defaults
    [currentDefaults setPersistentDomain:oldDefaultsDict forName:[[NSBundle mainBundle] bundleIdentifier]]];

    // Set the flag to avoid subsequent import of old defaults
    [currentDefaults setBool:YES forKey:@"importedOldDefaultsFromAAA"];
}

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122391

I'd say yes given the user defaults are stored in ~/Library/Preferences/com.domain.appname.plist (or if the app is sandboxed ~/Library/Containers/com.domain.appname/Data/Library/Preferences/com.domain.appname.plist).

Upvotes: 0

Related Questions