iPhone - upgrading from old app preferences

2019-06-10 04:55发布

If I build a 1.0 app with 2 strings in the defaults, using registerDefaults.
And in a 2.0 version, I decide to remove the first old string, and move the second one (changing its key string) with a new third one into an array.
How may I deal with this and how to deal with the changes that could have been made to the content through versions.

1.0 Prefs should be

StringKey    someValue  
DateKey      10/10/2010

1.1 Prefs should be

StringKey    someValue  
DateKey      2010/10/10

2.0 Prefs should be

Array  
    Item0 is    DateKey        10/10/2010  
    Item1 is    BadString      BadBadValue

1条回答
放荡不羁爱自由
2楼-- · 2019-06-10 05:03

If you've used registerDefaults: in version 1.0 of your app it's easy. When you stop to register those old values and they were not changed by the user they disappear from NSUserDefaults.

So ask NSUserDefaults for all objects that should be converted. If they exist convert them to the new format, save them in the NSUserDefaults and remove the old value.

Something like this should work

// check if you can get the old object. if it's there it was changed by the user
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"OldKey1"]) {
    // old key is present
    id oldObject = [[NSUserDefaults standardUserDefaults] objectForKey:@"OldKey1"];

    id newObject = ... // convert the old object to the new object
    [[NSUserDefaults standardUserDefaults] setObject:newObject forKey:@"NewKey1"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"OldKey1"];
}
else {
    // old key not there, do nothing
}

// register your new defaults...

If you haven't used registerDefaults: you have a problem now. Because you don't know if the object was changed by the user or if the object is simply your default. And you can't assume that the value is still in default state just because it has the same value as the default.

But what to do in this case? I would probably reset the value to default and show a UIAlert that tells the user to check the preferences because I did a mistake :-)

查看更多
登录 后发表回答