【发布时间】:2018-10-08 05:27:49
【问题描述】:
尝试添加新密钥“密码”。该应用程序的现有版本具有这些现有键“名称”、“IP”、“端口”,并已存储值。添加新键“密码”时,应用程序无法读取现有数据,并显示此错误“无法解码系统对象的名称”。来自以下代码:
guard let password = aDecoder.decodeObject(forKey: PropertyKey.password) as? String else {
os_log("Unable to decode the name for a System object.", log: OSLog.default, type: .debug)
return nil
}
我的问题是如何添加新键“密码”为所有现有的键控存档(数据/对象)分配默认值“123456”,而不破坏现有数据。
e.g.
name = "System01", ip = "10.0.0.3", port = "3535", password = "123456"
name = "System02", ip = "10.0.0.4", port = "3535", password = "123456"
=============================
import UIKit
import os.log
class System: NSObject, NSCoding {
//MARK: Properties
var name: String
var ip: String
var port: String
var password: String. // Added this new key
//MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("systems")
//MARK: Types
struct PropertyKey {
static let name = "name"
static let ip = "ip"
static let port = "port"
static let password = "password" // Added this new key
}
//MARK: Initialization
init(name: String, ip: String, port: String, password: String) {
// Initialize stored properties.
self.name = name
self.ip = ip
self.port = port
self.password = password // Added this new key
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(ip, forKey: PropertyKey.ip)
aCoder.encode(port, forKey: PropertyKey.port)
aCoder.encode(password, forKey: PropertyKey.password) // Added this new key
}
required convenience init?(coder aDecoder: NSCoder) {
// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else {
os_log("Unable to decode the name for a System object.", log: OSLog.default, type: .debug)
return nil
}
guard let ip = aDecoder.decodeObject(forKey: PropertyKey.ip) as? String else {
os_log("Unable to decode the name for a System object.", log: OSLog.default, type: .debug)
return nil
}
guard let port = aDecoder.decodeObject(forKey: PropertyKey.port) as? String else {
os_log("Unable to decode the name for a System object.", log: OSLog.default, type: .debug)
return nil
}
guard let password = aDecoder.decodeObject(forKey: PropertyKey.password) as? String else {
os_log("Unable to decode the name for a System object.", log: OSLog.default, type: .debug)
return nil
} // Added this new key
// Must call designated initializer.
self.init(name: name, ip: ip, port: port, password: password)
}
}
【问题讨论】:
-
很明显会发生崩溃。你试图阅读不存在的东西
-
这就是为什么我想知道如何添加新密钥并使其与现有数据一起使用
-
@Gereon 提供的答案应该可以正常工作