How do I use NSKeyArchiver and NSKeyunArchiver to backup and restore an array of floats? Is there any sample code anywhere?
I only knew there was a problem because I couldn't read the second file back.
So what is the situation ?
- do you write both files and get succes and success2 true ?
- Can you now read both files or not ?
Note: it normal you got it true even when you overwrote the first file.
Why don't you have a symmetric hanling for reading both ? The second is inside the if let of the first.
I would better write like this (and instrument the code to check what's going on.
Thanks to report result:
let theURL = getDocumentsDirectory().appendingPathComponent("tarfile")
if let data = NSMutableData(contentsOf: theURL) {
print("data read on", theURL)
let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data)
if let readArray = unarchiver.decodeObject(forKey: "starray") as? [Float] {
unarchiver.finishDecoding()
tarray = readArray
print("tarray read ", tarray)
}
} // MOVE CLOSING CURLY BRACE
let theURL2 = getDocumentsDirectory().appendingPathComponent("tipfile")
if let data2 = NSMutableData(contentsOf: theURL2) {
print("data2 read on", theURL2)
let unarchiver2 = NSKeyedUnarchiver(forReadingWith: data2 as Data)
if let readArray2 = unarchiver2.decodeObject(forKey: "stipray") as? [Float] {
unarchiver2.finishDecoding()
tipray = readArray2
print("tipray read ", tipray)
}
}