自升级到Swift 4.2之后,我发现许多NSKeyedUnarchiver和NSKeyedArchiver方法已被弃用,我们现在必须使用类型方法static func unarchivedObject<DecodedObjectType>(ofClass: DecodedObjectType.Type, from: Data) -> DecodedObjectType?
取消存档数据。
我已经成功地将定制类WidgetData的数组成功存档,该类是NSObject子类:
private static func archiveWidgetDataArray(widgetDataArray : [WidgetData]) -> NSData {
guard let data = try? NSKeyedArchiver.archivedData(withRootObject: widgetDataArray as Array, requiringSecureCoding: false) as NSData
else { fatalError("Can't encode data") }
return data
}
当我尝试取消存档这些数据时出现问题:
static func loadWidgetDataArray() -> [WidgetData]? {
if isKeyPresentInUserDefaults(key: USER_DEFAULTS_KEY_WIDGET_DATA) {
if let unarchivedObject = UserDefaults.standard.object(forKey: USER_DEFAULTS_KEY_WIDGET_DATA) as? Data {
//THIS FUNCTION HAS NOW BEEN DEPRECATED:
//return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [WidgetData]
guard let nsArray = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: unarchivedObject as Data) else {
fatalError("loadWidgetDataArray - Can't encode data")
}
guard let array = nsArray as? Array<WidgetData> else {
fatalError("loadWidgetDataArray - Can't get Array")
}
return array
}
}
return nil
}
但这失败了,因为不允许使用Array.self
而不是NSArray.self
。我在做错什么,如何解决这个问题以取消存档?
答案 0 :(得分:12)
您可以使用unarchiveTopLevelObjectWithData(_:)
来取消存档archivedData(withRootObject:requiringSecureCoding:)
存档的数据。 (我相信现在还不建议使用。)
但是在显示一些代码之前,您最好:
避免使用NSData
,而改用Data
避免使用try?
来处理对调试有用的错误信息
删除所有不需要的演员
尝试一下:
private static func archiveWidgetDataArray(widgetDataArray : [WidgetData]) -> Data {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: widgetDataArray, requiringSecureCoding: false)
return data
} catch {
fatalError("Can't encode data: \(error)")
}
}
static func loadWidgetDataArray() -> [WidgetData]? {
guard
isKeyPresentInUserDefaults(key: USER_DEFAULTS_KEY_WIDGET_DATA), //<- Do you really need this line?
let unarchivedObject = UserDefaults.standard.data(forKey: USER_DEFAULTS_KEY_WIDGET_DATA)
else {
return nil
}
do {
guard let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(unarchivedObject) as? [WidgetData] else {
fatalError("loadWidgetDataArray - Can't get Array")
}
return array
} catch {
fatalError("loadWidgetDataArray - Can't encode data: \(error)")
}
}
但是,如果要制作新应用,则最好考虑使用Codable
。
答案 1 :(得分:4)
unarchiveTopLevelObjectWithData(_:)
也已弃用。因此,要在没有安全编码的情况下取消存档数据,您需要:
NSKeyedUnarchiver
创建init(forReadingFrom: Data)
requiresSecureCoding
设置为false。decodeObject(of: [AnyClass]?, forKey: String) -> Any?
来获取对象,只需使用适当的类并以NSKeyedArchiveRootObjectKey
作为键即可。答案 2 :(得分:2)
if #available(iOS 12.0, *) {
guard let unarchivedFavorites = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(favoritesData!)
else {
return
}
self.channelFavorites = unarchivedFavorites as! [ChannelFavorite]
} else {
if let unarchivedFavorites = NSKeyedUnarchiver.unarchiveObject(with: favoritesData!) as? [ChannelFavorite] {
self.channelFavorites = unarchivedFavorites
}
//获得数据
if #available(iOS 12.0, *) {
// use iOS 12-only feature
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: channelFavorites, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: "channelFavorites")
} catch {
return
}
} else {
// handle older versions
let data = NSKeyedArchiver.archivedData(withRootObject: channelFavorites)
UserDefaults.standard.set(data, forKey: "channelFavorites")
}
这是我更新代码及其对我有用的方式
答案 3 :(得分:1)
您可能正在寻找:
if let widgetsData = UserDefaults.standard.data(forKey: USER_DEFAULTS_KEY_WIDGET_DATA) {
if let widgets = (try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, WidgetData.self], from: widgetsData)) as? [WidgetData] {
// your code
}
}
答案 4 :(得分:1)
Swift 5- IOS 13
guard let mainData = UserDefaults.standard.object(forKey: "eventDetail") as? NSData
else {
print(" data not found in UserDefaults")
return
}
do {
guard let finalArray =
try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(mainData as Data) as? [EventDetail]
else {
return
}
self.eventDetail = finalArray
}
答案 5 :(得分:0)
由于iOS 14.3之后也不再推荐使用 unarchiveTopLevelObjectWithData ,因此现在只有Hopreeeenjust's answer是正确的。
但是,如果您不需要NSSecureCoding,也可以使用answer of Maciej S
通过向NSCoding协议添加扩展,非常容易使用它:
extension NSCoding where Self: NSObject {
static func unsecureUnarchived(from data: Data) -> Self? {
do {
let unarchiver = try NSKeyedUnarchiver(forReadingFrom: data)
unarchiver.requiresSecureCoding = false
let obj = unarchiver.decodeObject(of: self, forKey: NSKeyedArchiveRootObjectKey)
if let error = unarchiver.error {
print("Error:\(error)")
}
return obj
} catch {
print("Error:\(error)")
}
return nil
}
}
此扩展为取消存档,例如您只需要使用NSArray:
let myArray = NSArray.unsecureUnarchived(from: data)
对于Objective C,请使用NSObject类别:
+ (instancetype)unsecureUnarchivedFromData:(NSData *)data {
NSError * err = nil;
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData: data error: &err];
unarchiver.requiresSecureCoding = NO;
id res = [unarchiver decodeObjectOfClass:self forKey:NSKeyedArchiveRootObjectKey];
err = err ?: unarchiver.error;
if (err != nil) {
NSLog(@"NSKeyedUnarchiver unarchivedObject error: %@", err);
}
return res;
}
请注意,如果requireSecureCoding为false,则实际上未检查未归档对象的类,即使从错误的类调用它,目标c代码也会返回有效结果。 从错误的类调用时,快速代码返回nil(由于可选的强制转换),但没有错误。