In my application, the user data getting after login is saved in the preferences as below. The xcode shows the warning that NSKeyedUnarchiver.unarchiveObject(with:) and NSKeyedArchiver.archivedData(withRootObject:) are deprecated from iOS 12. But application is working fine till the latest iOS versions. To make it stable, how can I change it to unarchivedObjectOfClass:fromData:error: which is recommended.
static var userLoginResponse : LoginModel? {
get {
if let data = UserDefaults.standard.data(forKey: "userLoginResponse"), let respData = NSKeyedUnarchiver.unarchiveObject(with: data) as? Data {
return LoginModel(data: respData)
}
return nil
}
set {
if let value = newValue?.toJsonData() {
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: value), forKey: "userLoginResponse")
} else {
UserDefaults.standard.setValue(nil, forKey: "userLoginResponse")
}
}
}
As per the apple documentation, unarchivedObjectOfClass:fromData:error: will unarchive the data saved as NSCoded object. How can I change this existing implementation without affect the existing app users ?
2
Answers
Replace the function by:
You are going to archive
Data
which is already PropertyList compliant. Remove theNSKeyed(Un)archiver
stuff.Side-note: Never use
setValue(_:forKey:)
unless you mean KVC (you don’t).