我想在取消归档对象时删除警告,因此我尝试实现:
func retrieveRepository(componentName:String, ofClass: AnyClass<NSObject, NSCoding>)->Any?{
let fileUrl = getDocumentsDirectory().appendingPathComponent(componentName)
do{
let rawdata = try Data(contentsOf: fileUrl)
let optionalQueue = try NSKeyedUnarchiver.unarchivedObject(ofClass: ofClass, from:rawdata)
return optionalQueue
} catch {
return nil
}
}
实际上,unarchiveObject 需要要取消存档的类的名称,该类必须同时采用 NSObject 和 NSCoding。然而,这种实施总体上是错误的。如何正确实施呢?
谢谢,法布里齐奥
我尝试删除警告。
您可以使用泛型类型重写该函数,如下所示:
func retrieveRepository<T: NSObject & NSCoding>(componentName: String, ofClass: T) -> Any? {
let fileUrl = getDocumentsDirectory().appendingPathComponent(componentName)
do {
let rawdata = try Data(contentsOf: fileUrl)
let optionalQueue = try NSKeyedUnarchiver.unarchivedObject(ofClass: ofClass, from: rawdata)
return optionalQueue
} catch {
return nil
}
}