Ios 使用NSKeyedUnarchiver解码URL对象数组
我正在尝试使用NSKeyedUnarchiver解码URL对象数组。代码如下:Ios 使用NSKeyedUnarchiver解码URL对象数组,ios,swift,nskeyedunarchiver,Ios,Swift,Nskeyedunarchiver,我正在尝试使用NSKeyedUnarchiver解码URL对象数组。代码如下: let urlArray: [URL] = [URL(string: "https://apple.com")!, URL(string: "https://google.com")!] do { let archivedUrls = try NSKeyedArchiver.archivedData(withRootObject: urlArray, requi
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
)}'.}
如果我用替换让我尝试NSKeyedUnarchiver.unarchivedObject(类:NSArray.self,from:archivedUrls)
,让我尝试NSKeyedUnarchiver.unarchivedObject(类:[NSArray.self,NSURL.self],from:archivedUrls)
,那么它就工作了。但这意味着它可以解码NSArray
或NSURL
对象,而不是包含NSURL
对象的NSArray
如果我将数组改为字符串的数组
,则一切正常:
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)
}
有人对这种行为有解释吗?如果您不需要安全编码(
要求安全编码:false
),您可以使用unarchiveTopLevelObjectWithData(:)
)
或者您可以使用unarchivedObject(对于类:from:)
指定存档中包含的类型
NSString
似乎是此规则的例外
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)
}
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)
}