iPhone - upgrading from old app preferences

三世轮回 提交于 2019-12-23 05:48:46

问题


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:


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 :-)



来源:https://stackoverflow.com/questions/5443252/iphone-upgrading-from-old-app-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!