gpt4 book ai didi

ios - 使用 NSKeyedUnarchiver 解码 URL 对象数组

转载 作者:行者123 更新时间:2023-12-01 16:13:18 30 4
gpt4 key购买 nike

我正在尝试使用 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) ,然后它工作。但这意味着它可以解码 NSArrayNSURL对象,而不是 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com