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

标签 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, 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/

相关文章:

ios - 等待 Testflight 上的 Beta App Review

ios - SpriteKit 运行 Action :withKey: combined with repeatActionForever: crashes app

swift - 我有一个带有图像的 UItableView 单元格,但无法获取图像单击以允许参数

swift - 使用 NSKeyedUnarchiver 反序列化 GKGraphNode 的子类

ios - NSKeyedArchiver 继承自 NSCoder 为什么会存在 NSKeyedUnarchiver?

ios - 如何在 swift 中全局使用解析值

c# - UITest 失败,返回 : "SetUp : System.InvalidOperationException"

swift - 如何在 WKWebView 中捕获通知?

ios - UIView animate withDuration 不会在 iOS 9.3.5 上调用完成处理程序

ios - Swift 唯一防止 NSKeyedUnarchiver.decodeObject 崩溃的方法?