1
我試圖使用存儲一個UserDefaults
自定義類的數組。自定義類是使用字符串和CLLocationCoordinate2D
的混合物註解。自定義類存儲 - 不能編碼結構
我打電話ArchiveUtil.savePins(pins: pins)
當我在地圖視圖執行長按手勢。
不過,我得到一個錯誤
- [的NSKeyedArchiver encodeValueOfObjCType:在:]:此歸檔無法編碼結構
任何想法我做錯了嗎?
謝謝,下面的代碼:
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()
}
}