这是我的Codable类(class):
class SensorOutput: Codable {
var timeStamp: Date?
var gyroX: Double?
var gyroY: Double?
var gyroZ: Double?
var accX: Double?
var accY: Double?
var accZ: Double?
var magX: Double?
var magY: Double?
var magZ: Double?
init() {}
}
在这里,我尝试编写并读取该类的对象以归档:
let myData = SensorOutput()
myData.timeStamp = Date()
myData.gyroX = 0.0
myData.gyroY = 0.0
myData.gyroZ = 0.0
myData.accX = 0.0
myData.accY = 0.0
myData.accZ = 0.0
myData.magX = 0.0
myData.magY = 0.0
myData.magZ = 0.0
NSKeyedArchiver.archiveRootObject(myData, toFile: filePath)
if let Data = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? SensorOutput {
print (Data)
}
这在归档过程中产生了一个错误:
Error screenshot
PS:我以这种方式收到的filePath:
var filePath: String {
//1 - manager lets you examine contents of a files and folders in your app; creates a directory to where we are saving it
let manager = FileManager.default
//2 - this returns an array of urls from our documentDirectory and we take the first path
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
print("this is the url path in the documentDirectory \(String(describing: url))")
//3 - creates a new path component and creates a new file called "Data" which is where we will store our Data array.
return (url!.appendingPathComponent("Data").path)
}
读/写可用于Int或Double以及其他受支持的类型,但不适用于我的类型。怎么了?
最佳答案
尽管@matt的答案包含解决问题的基本信息,但是如果您不熟悉Swift和iOS编程,如何应用这些信息可能并不明显。
您尝试使用NSKeyedArchiver.archiveRootObject(_:toFile:)
(这是一个类方法),因此不必创建NSKeyedArchiver
的实例。由于encodeEncodable(_:forKey:)
是实例方法,而不是类方法,因此您需要创建NSKeyedArchiver
实例才能使用它。您还需要为存档器创建一个NSMutableData
,以将字节追加到该存档器,并且在对对象进行编码后必须调用finishEncoding
。
let sensorOutput = SensorOutput()
sensorOutput.timeStamp = Date()
let mutableData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: mutableData)
try! archiver.encodeEncodable(sensorOutput, forKey: NSKeyedArchiveRootObjectKey)
archiver.finishEncoding()
// You can now write mutableData to a file or send it to your server
// or whatever.
同样,您尝试使用
NSKeyedUnarchiver.unarchiveObject(withFile:)
(这是一个类方法),但是您需要使用decodeDecodable(_:forKey:)
或decodeTopLevelDecodable(_:forKey:)
(这是实例方法)。因此,您需要读入存档数据并使用它来创建NSKeyedUnarchiver
的实例。// Read in the data from a file or your server or whatever.
// I'll just make an immutable copy of the archived data for this example.
let data = mutableData.copy() as! Data
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
do {
if let sensorOutputCopy = try unarchiver.decodeTopLevelDecodable(SensorOutput.self, forKey: NSKeyedArchiveRootObjectKey) {
print("deserialized sensor output: \(sensorOutputCopy)")
}
} catch {
print("unarchiving failure: \(error)")
}
(我更喜欢
decodeTopLevelDecodable
方法而不是decodeDecodable
,因为它会引发Swift错误,而不是在存档损坏时崩溃。)关于ios - NSKeyedArchiver不存档我的Codable类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49951731/