Attempt to insert non-property list object when tr

2020-01-24 12:42发布

问题:

I have a simple object which conforms to the NSCoding protocol.

import Foundation

class JobCategory: NSObject, NSCoding {
    var id: Int
    var name: String
    var URLString: String

    init(id: Int, name: String, URLString: String) {
        self.id = id
        self.name = name
        self.URLString = URLString
    }

    // MARK: - NSCoding
    required init(coder aDecoder: NSCoder) {
        id = aDecoder.decodeObject(forKey: "id") as? Int ?? aDecoder.decodeInteger(forKey: "id")
        name = aDecoder.decodeObject(forKey: "name") as! String
        URLString = aDecoder.decodeObject(forKey: "URLString") as! String
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(id, forKey: "id")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(URLString, forKey: "URLString")
    }
}

I'm trying to save an instance of it in UserDefaults but it keeps failing with the following error.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object for key jobCategory'

This is the code where I'm saving in UserDefaults.

enum UserDefaultsKeys: String {
    case jobCategory
}

class ViewController: UIViewController {

    @IBAction func didTapSaveButton(_ sender: UIButton) {
        let category = JobCategory(id: 1, name: "Test Category", URLString: "http://www.example-job.com")

        let userDefaults = UserDefaults.standard
        userDefaults.set(category, forKey: UserDefaultsKeys.jobCategory.rawValue)
        userDefaults.synchronize()
    }
}

I replaced the enum value to key with a normal string but the same error still occurs. Any idea what's causing this?

回答1:

You need to create Data instance from your JobCategory instance using NSKeyedArchiver.archivedData(withRootObject:) and store that Data instance in UserDefaults and later unarchive using NSKeyedUnarchiver.unarchiveObject(with:), So try like this.

For Storing data in UserDefaults

let category = JobCategory(id: 1, name: "Test Category", URLString: "http://www.example-job.com")
let encodedData = NSKeyedArchiver.archivedData(withRootObject: category)
let userDefaults = UserDefaults.standard
userDefaults.set(encodedData, forKey: UserDefaultsKeys.jobCategory.rawValue)

For retrieving data from UserDefaults

let decoded  = UserDefaults.standard.object(forKey: UserDefaultsKeys.jobCategory.rawValue) as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! JobCategory
print(decodedTeams.name)


回答2:

Update Swift 4, Xcode 10

I have written a struct around it for easy access.

//set, get & remove User own profile in cache
struct UserProfileCache {
    static let key = "userProfileCache"
    static func save(_ value: Profile!) {
         UserDefaults.standard.set(try? PropertyListEncoder().encode(value), forKey: key)
    }
    static func get() -> Profile! {
        var userData: Profile!
        if let data = UserDefaults.standard.value(forKey: key) as? Data {
            userData = try? PropertyListDecoder().decode(Profile.self, from: data)
            return userData!
        } else {
            return userData
        }
    }
    static func remove() {
        UserDefaults.standard.removeObject(forKey: key)
    }
}

Profile is a Json encoded object.

struct Profile: Codable {
let id: Int!
let firstName: String
let dob: String!
}

Usage:

//save details in user defaults...
UserProfileCache.save(profileDetails)

Hope that helps!!!

Thanks



回答3:

Save dictionary Into userdefault

let data = NSKeyedArchiver.archivedData(withRootObject: DictionaryData)
UserDefaults.standard.set(data, forKey: kUserData)

Retrieving the dictionary

let outData = UserDefaults.standard.data(forKey: kUserData)
let dict = NSKeyedUnarchiver.unarchiveObject(with: outData!) as! NSDictionary