Frederik Norlyk Eriksen Frederik Norlyk Eriksen - 1 month ago 6
Objective-C Question

Replacing an Objective-C iOS app with a brand new Swift app while keeping values from NSUserDefaults

I have a general question when it comes to replacing an old application with a brand new one. The old application is several years old and written in Objective-C and I am developing an update from scratch in Swift.

I am wondering how to preserve a variable from the old app called "

email_preference
" which is stored in
NSUserDefaults
. How do I access the variable when the update is complete, and how do I test that I get the variable correctly (I feel like I have to do it correctly the first time or the value will be lost)?

These are the mentions I have found in the old code:

//Saves the email
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.email.text forKey:@"email_preference"];

//Gets the email
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *email = [defaults objectForKey:@"email_prefe


Thank you.

Answer

If the "new" app has the same bundle identifier as the "old" one, you can get the saved email just like this:

let email = UserDefaults.standard.object(forKey: "email_preference")
Comments