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
相关产品推荐
相关产品推荐

