skip to Main Content

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


  1. Replace the function by:

    try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSData.self, from: data) as? Data
    
    Login or Signup to reply.
  2. You are going to archive Data which is already PropertyList compliant. Remove the NSKeyed(Un)archiver stuff.

    static var userLoginResponse : LoginModel? {
        get {
            guard let data = UserDefaults.standard.data(forKey: "userLoginResponse") else { return nil }
            return LoginModel(data: data)
        }
        set {
            UserDefaults.standard.set(newValue?.toJsonData(), forKey: "userLoginResponse")
        }
    }
    

    Side-note: Never use setValue(_:forKey:) unless you mean KVC (you don’t).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search