You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift归档迁移:无法启用unarchivedObject新方法

归档与解归档代码迁移方案

归档代码修改(兼容新API)

原有归档逻辑可直接沿用,archivedData(withRootObject:requiringSecureCoding:)目前未被弃用。若后续需启用安全编码,仅需将requiringSecureCoding设为true即可:

var selectedAmenities = [String: String]()

var archivedAmenities: Data?
do {
    archivedAmenities = try NSKeyedArchiver.archivedData(
        withRootObject: selectedAmenities,
        requiringSecureCoding: false
    )
} catch {
    print("Couldn't archive the Amenities.")
}

解归档代码修改(替换弃用API)

用NSKeyedUnarchiver.unarchivedObject(ofClass:from:)替代弃用的unarchiveTopLevelObjectWithData方法。由于Swift字典[String: String]归档后对应Objective-C的NSDictionary类型,需指定目标类为NSDictionary.self,再转换为Swift字典:

var selectedAmenities = [String: String]()

guard let amenitiesData = theSite.amenities else {
    print("No amenities data to unarchive.")
    return
}

do {
    if let unArchivedAmenities = try NSKeyedUnarchiver.unarchivedObject(
        ofClass: NSDictionary.self,
        from: amenitiesData
    ) as? [String: String] {
        selectedAmenities = unArchivedAmenities
    } else {
        print("Unarchived data is not a valid [String: String] dictionary.")
    }
} catch {
    print("Couldn't unarchive the Amenities: \(error.localizedDescription)")
}

关键说明

  • 规避强制解包风险:新增guard let校验数据是否存在,用as?替代as!防止类型转换崩溃
  • 匹配正确归档类型:Swift字典归档后会转为NSDictionary,解归档时必须指定该类才能正确解析
  • 优化错误排查:捕获错误时打印具体描述,便于定位问题

内容的提问来源于stack exchange,提问作者Kent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:05:06