I have created a generic function
for NSKeyedArchiver
and NSKeyedUnarchiver
. I am able to archive the array data but while doing unarchive facing an issue. Below is my code:
NSKeyedArchiver code:
func cacheData<T>(data: T) {
do {
let codedData = try NSKeyedArchiver.archivedData(withRootObject: data, requiringSecureCoding: false)
} catch {
print("Exception while caching data \(error)")
}
}
NSKeyedUnarchiver code:
func getCacheData<T>(encodedData: Data, ofClass: T.Type) -> [T]? {
do{
if let decodedData = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, T.self as! AnyClass], from: encodedData){
return decodedData as? [T]
}
} catch {
print("Exception while decode array cache data \(error)")
}
return nil
}
Above code works fine for having only strings
, integers
variables but it failed if having custom classes
variables. How to allow these custom classes in NSKeyedUnarchiver
.
I am getting below error:
Exception while decode array cache data Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'customclass1' was of unexpected class 'CustomClass1'. Allowed classes are '{( NSArray, MainClass )}'." UserInfo={NSDebugDescription=value for key 'customclass2' was of unexpected class 'CustomClass2'. Allowed classes are '{( NSArray, MainClass )}'.}
Any idea how to solve this?