如何将包含CLLocationCoordinate2D属性的自定义对象存储到UserDefaults
CLLocationCoordinate2D 实现Codable协议方案
CLLocationCoordinate2D仅包含latitude(纬度)和longitude(经度)两个原生支持Codable的Double类型属性,直接针对这两个属性做编解码即可,完整实现代码如下:
extension CLLocationCoordinate2D: Codable { // 定义编解码对应的key enum CodingKeys: String, CodingKey { case latitude case longitude } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) latitude = try container.decode(Double.self, forKey: .latitude) longitude = try container.decode(Double.self, forKey: .longitude) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(latitude, forKey: .latitude) try container.encode(longitude, forKey: .longitude) } }
配套UserDefaults存储使用示例
完成上述扩展后,整个Note结构体就可以正常做JSON编解码,直接存入UserDefaults:
// 存储笔记到本地 let sampleNote = Note( id: UUID(), title: "探店笔记", body: "中关村咖啡好喝", location: CLLocationCoordinate2D(latitude: 39.9847, longitude: 116.3047) ) if let encodedData = try? JSONEncoder().encode(sampleNote) { UserDefaults.standard.set(encodedData, forKey: "savedNote") } // 从本地读取笔记 if let savedData = UserDefaults.standard.data(forKey: "savedNote"), let decodedNote = try? JSONDecoder().decode(Note.self, from: savedData) { print("读取到的坐标纬度:\(decodedNote.location.latitude)") print("读取到的坐标经度:\(decodedNote.location.longitude)") }
注意:建议生产环境使用时额外增加坐标合法性校验,避免非法坐标值导致后续位置功能崩溃。
内容的提问来源于stack exchange,提问作者user1895268
相关产品推荐
相关产品推荐

