我正在尝试使用 NSKeyedUnarchiver 解码 URL 对象数组。这是代码:
let urlArray: [URL] = [URL(string: "https://apple.com")!,
URL(string: "https://google.com")!]
do {
let archivedUrls = try NSKeyedArchiver.archivedData(withRootObject: urlArray, requiringSecureCoding: false)
let _ = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: archivedUrls)
} catch {
print(error)
}
我收到以下错误:
Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'NS.objects' was of unexpected class 'NSURL'. Allowed classes are '{(
NSArray
)}'." UserInfo={NSDebugDescription=value for key 'NS.objects' was of unexpected class 'NSURL'. Allowed classes are '{(
NSArray
)}'.}
如果我替换
let _ = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: archivedUrls)
通过 let _ = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, NSURL.self], from: archivedUrls)
,然后它工作。但这意味着它可以解码 NSArray
或 NSURL
对象,而不是 NSArray
包含 NSURL
对象。如果我将数组更改为
String
的数组相反,一切正常:let stringArray: [String] = ["string", "string2"]
do {
let archivedStrings = try NSKeyedArchiver.archivedData(withRootObject: stringArray, requiringSecureCoding: false)
let _ = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: archivedStrings)
} catch {
print(error)
}
有人对这种行为有解释吗?
最佳答案
如果您不需要安全编码 ( requiringSecureCoding: false
),您可以使用 unarchiveTopLevelObjectWithData(_:)
.
do {
let archivedUrls = try NSKeyedArchiver.archivedData(withRootObject: urlArray, requiringSecureCoding: false)
if let urls = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(archivedUrls) as? [URL] {
print(urls)
} else {
print("not URLs")
}
} catch {
print(error)
}
或者您可以使用
unarchivedObject(ofClasses:from:)
指定存档中包含的类型。 .do {
let archivedUrls = try NSKeyedArchiver.archivedData(withRootObject: urlArray, requiringSecureCoding: true)
if let urls = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self, NSURL.self], from: archivedUrls) as? [URL] {
print(urls)
} else {
print("not URLs")
}
} catch {
print(error)
}
NSString
似乎是这个规则的一个异常(exception)。
关于ios - 使用 NSKeyedUnarchiver 解码 URL 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59020621/