我有一个符合NSCoding
协议的简单对象。
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")
}
}
我正在尝试在UserDefaults
中保存它的一个实例,但它仍然失败,出现以下错误。
由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'尝试为关键jobCategory插入非属性列表对象'
这是我在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()
}
}
我用一个普通的字符串将枚举值替换为key,但仍然会出现相同的错误。知道是什么导致了这个吗?
你需要使用Data
从你的JobCategory
实例创建NSKeyedArchiver.archivedData(withRootObject:)
实例并将Data
实例存储在UserDefaults
中,然后使用NSKeyedUnarchiver.unarchiveObject(with:)
解压缩,所以试试这样。
用于在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)
用于从UserDefaults
检索数据
let decoded = UserDefaults.standard.object(forKey: UserDefaultsKeys.jobCategory.rawValue) as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! JobCategory
print(decodedTeams.name)
更新Swift 4,Xcode 10
我已经围绕它编写了一个结构,以便于访问。
//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是一个Json编码对象。
struct Profile: Codable {
let id: Int!
let firstName: String
let dob: String!
}
用法:
//save details in user defaults...
UserProfileCache.save(profileDetails)
希望有所帮助!
谢谢
将字典保存到userdefault
let data = NSKeyedArchiver.archivedData(withRootObject: DictionaryData)
UserDefaults.standard.set(data, forKey: kUserData)
检索字典
let outData = UserDefaults.standard.data(forKey: kUserData)
let dict = NSKeyedUnarchiver.unarchiveObject(with: outData!)as!NSDictionary