我正在尝试使用UserDefaults
存储自定义类的数组。自定义类用于使用字符串和CLLocationCoordinate2D
的混合注释。
当我在地图视图中执行长按手势时,我正在呼叫ArchiveUtil.savePins(pins: pins)
。
然而,我收到错误
- [NSKeyedArchiver encodeValueOfObjCType:at:]:此归档程序无法对结构进行编码'
任何想法我做错了什么?
谢谢,代码如下:
class PinLocation: NSObject, NSCoding, MKAnnotation {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
init(name:String, description: String, lat:CLLocationDegrees,long:CLLocationDegrees){
title = name
subtitle = description
coordinate = CLLocationCoordinate2DMake(lat, long)
}
required init?(coder aDecoder: NSCoder) {
title = aDecoder.decodeObject(forKey: "title") as? String
subtitle = aDecoder.decodeObject(forKey: "subtitle") as? String
coordinate = aDecoder.decodeObject(forKey: "coordinate") as! CLLocationCoordinate2D
}
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: "title")
aCoder.encode(subtitle, forKey: "subtitle")
aCoder.encode(coordinate, forKey: "coordinate")
}
}
class ArchiveUtil {
private static let PinKey = "PinKey"
private static func archivePins(pin: [PinLocation]) -> NSData{
return NSKeyedArchiver.archivedData(withRootObject: pin as NSArray) as NSData
}
static func loadPins() -> [PinLocation]? {
if let unarchivedObject = UserDefaults.standard.object(forKey: PinKey) as? Data{
return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [PinLocation]
}
return nil
}
static func savePins(pins: [PinLocation]?){
let archivedObject = archivePins(pin: pins!)
UserDefaults.standard.set(archivedObject, forKey: PinKey)
UserDefaults.standard.synchronize()
}
}
答案 0 :(得分:2)
错误很明显:CLLocationCoordinate2D
是struct
而此归档程序无法对结构进行编码。
一个简单的解决方法是分别对latitude
和longitude
进行解码和解码。
顺便说一句,由于两个String
属性都使用非可选值初始化,因此将它们声明为非可选属性。如果它们不被改变,则将它们声明为常量(let
)
var title: String
var subtitle: String
...
required init?(coder aDecoder: NSCoder) {
title = aDecoder.decodeObject(forKey: "title") as! String
subtitle = aDecoder.decodeObject(forKey: "subtitle") as! String
let latitude = aDecoder.decodeDouble(forKey: "latitude")
let longitude = aDecoder.decodeDouble(forKey: "longitude")
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: "title")
aCoder.encode(subtitle, forKey: "subtitle")
aCoder.encode(coordinate.latitude, forKey: "latitude")
aCoder.encode(coordinate.longitude, forKey: "longitude")
}