Certainly 👌! The full class is below. Note that this is a mock example, but it does reflect and represent my real class pretty identically.
import Foundation
class MyData: NSObject, NSSecureCoding {
public class var supportsSecureCoding: Bool { true }
var id: Int?
var isModified: Bool?
var modifyDate: Date?
var myIntegers: [Int]?
var myEmbedIntegers: [[[Int]]]?
var myBooleans: [Bool]?
var myEmbedBooleans: [[Bool]]?
init(_id: Int, _isModified: Bool, _modifyDate: Date, _myIntegers: [Int], _myEmbedIntegers: [[[Int]]], _myBooleans: [Bool], _myEmbedBooleans: [[Bool]]) {
id = _id
isModified = _isModified
modifyDate = _modifyDate
myIntegers = _myIntegers
myEmbedIntegers = _myEmbedIntegers
myBooleans = _myBooleans
myEmbedBooleans = _myEmbedBooleans
}
required convenience init(coder decoder: NSCoder) {
let id = decoder.decodeInteger(forKey: "id")
let isModified = decoder.decodeBool(forKey: "isModified")
let modifyDate = decoder.decodeObject(of: NSDate.self, forKey: "modifyDate")! as Date
// Here's where the errors happen: The four lines underneath return nil, which in this case cause crashes due to force unwrapping.
let myIntegers = decoder.decodeObject(forKey: "myIntegers") as! [Int]
let myEmbedIntegers = decoder.decodeObject(forKey: "myEmbedIntegers") as! [[[Int]]]
let myBooleans = decoder.decodeObject(forKey: "myBooleans") as! [Bool]
let myEmbedBooleans = decoder.decodeObject(forKey: "myEmbedBooleans") as! [[Bool]]
self.init(_id: id, _isModified: isModified, _modifyDate: modifyDate, _myIntegers: myIntegers, _myEmbedIntegers: myEmbedIntegers, _myBooleans: myBooleans, _myEmbedBooleans: myEmbedBooleans)
}
func encode(with coder: NSCoder) {
coder.encode(id!, forKey: "id")
coder.encode(isModified!, forKey: "isModified")
coder.encode(modifyDate!, forKey: "modifyDate")
coder.encode(myIntegers!, forKey: "myIntegers")
coder.encode(myEmbedIntegers!, forKey: "myEmbedIntegers")
coder.encode(myBooleans!, forKey: "myBooleans")
coder.encode(myEmbedBooleans!, forKey: "myEmbedBooleans")
}
}
And they are called using these interfaces:
public func loadMyData() -> [MyData]? {
do {
let data = try Data(contentsOf: myDataPath())
let myData = try NSKeyedUnarchiver.unarchivedArrayOfObjects(ofClass: MyData.self, from: data)
return myData
} catch {}
return nil
}
public func saveMyData(_ mixData: [MyData]) {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: myData, requiringSecureCoding: false)
try data.write(to: myDataPath())
} catch {}
}
private func myDataPath() -> URL {
return (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as URL).appendingPathComponent("MyData.plist")
}
Topic:
App & System Services
SubTopic:
General
Tags: