在Swift 3中,可以使用以下步骤来实现持久化和检索NSCoding兼容对象到应用程序文档目录:
class CustomObject: NSObject, NSCoding {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
required convenience init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: "name") as? String,
let age = aDecoder.decodeObject(forKey: "age") as? Int else {
return nil
}
self.init(name: name, age: age)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(age, forKey: "age")
}
}
let customObject = CustomObject(name: "John", age: 25)
if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let archiveURL = documentsDirectory.appendingPathComponent("CustomObjectData")
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: customObject, requiringSecureCoding: false)
try data.write(to: archiveURL)
} catch {
print("Failed to save data: \(error)")
}
}
if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let archiveURL = documentsDirectory.appendingPathComponent("CustomObjectData")
do {
let data = try Data(contentsOf: archiveURL)
if let customObject = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? CustomObject {
print("Name: \(customObject.name), Age: \(customObject.age)")
}
} catch {
print("Failed to retrieve data: \(error)")
}
}
这样就可以在Swift 3中使用持久化和检索NSCoding兼容对象到应用程序文档目录了。
腾讯云相关产品和产品介绍链接地址:
请注意,以上仅为腾讯云的相关产品示例,其他云计算品牌商也提供类似的产品和服务。
领取专属 10元无门槛券
手把手带您无忧上云