2017-10-15 52 views
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() 
    } 

} 

回答

1

的錯誤是很清楚的:CLLocationCoordinate2D是一個struct該歸檔無法編碼結構

一個簡單的解決方法是將烯並分別解碼latitudelongitude

順便說一句,因爲這兩個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") 
}