这是Swift 4.2版本:
假设您有自定义类CustomClass。确保它符合NSSecureCoding协议。
class CustomClass: NSObject, NSCopying, NSSecureCoding {
var longName: String
var shortName: String
init(longName: String, shortName: String) {
self.longName = longName
self.shortName = shortName
}
// MARK: - NSCoding Protocol
required convenience init(coder aDecoder: NSCoder) {
let longName = (aDecoder.decodeObject(forKey: "longName") as? String ?? "")
let shortName = (aDecoder.decodeObject(forKey: "shortName") as? String ?? "")
self.init(longName: longName, shortName: shortName)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.longName, forKey: "longName")
aCoder.encode(self.shortName, forKey: "shortName")
}
// MARK: - NSSecureCoding Protocol
static var supportsSecureCoding: Bool = true
// MARK: - NSCopying Protocol
func copy(with zone: NSZone? = nil) -> Any {
return CustomClass(longName: self.longName, shortName: self.shortName)
}
}
首先,您需要将对象数组转换为二进制数据并将其存档:
let userDefaults = UserDefaults.standard
let customObjectsData = try? NSKeyedArchiver.archivedData(withRootObject: customObjectsArray, requiringSecureCoding: true)
userDefaults.set(customObjectsData, forKey: USER_DEFAULTS_DATA_KEY)
userDefaults.synchronize()
在此之后,您可以从UserDefaults中读取数据并取消归档:
if let customObjectsData = UserDefaults.standard.data(forKey: USER_DEFAULTS_DATA_KEY) {
if let customObjects = (try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, CustomObject.self], from: customObjectsData)) as? [CustomObject] {
// your code
}
}