Here is Swift 4.2 version:
Let's assume you have you custom class CustomClass.
Make sure it conforms NSSecureCoding protocol.
class CustomClass: NSObject, NSCopying, NSSecureCoding {
var longName: String
var shortName: String
init(longName: String, shortName: String) {
self.longName = longName
self.shortName = shortName
}
// MARK: - NSCoding Protocol
required convenience init(coder aDecoder: NSCoder) {
let longName = (aDecoder.decodeObject(forKey: "longName") as? String ?? "")
let shortName = (aDecoder.decodeObject(forKey: "shortName") as? String ?? "")
self.init(longName: longName, shortName: shortName)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.longName, forKey: "longName")
aCoder.encode(self.shortName, forKey: "shortName")
}
// MARK: - NSSecureCoding Protocol
static var supportsSecureCoding: Bool = true
// MARK: - NSCopying Protocol
func copy(with zone: NSZone? = nil) -> Any {
return CustomClass(longName: self.longName, shortName: self.shortName)
}
}
First you need to convert your objects array to the binary data and archive it:
let userDefaults = UserDefaults.standard
let customObjectsData = try? NSKeyedArchiver.archivedData(withRootObject: customObjectsArray, requiringSecureCoding: true)
userDefaults.set(customObjectsData, forKey: USER_DEFAULTS_DATA_KEY)
userDefaults.synchronize()
After this you are able to read the data from the UserDefaults and unarchive it:
if let customObjectsData = UserDefaults.standard.data(forKey: USER_DEFAULTS_DATA_KEY) {
if let customObjects = (try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, CustomObject.self], from: customObjectsData)) as? [CustomObject] {
// your code
}
}