0
嘗試將MKMapItem保存爲我的自定義類的一部分。非兼容對象的NSCoding(MKMapItem)
import UIKit
import MapKit
class Place: NSObject, NSCoding {
var mapItem : MKMapItem!
var type : Category!
init(mapItem: MKMapItem, type: Category) {
self.mapItem = mapItem
self.type = type
}
// MARK: NSCoding
required init?(coder decoder: NSCoder) {
mapItem = decoder.decodeObject(forKey: "mapItem") as! MKMapItem?
type = decoder.decodeObject(forKey: "type") as! Category?
}
func encode(with coder: NSCoder) {
coder.encode(mapItem, forKey: "mapItem")
coder.encode(type, forKey: "type")
}
}
但是這不起作用,因爲MKMapItem不符合NSCoding(編譯器不抱怨,雖然)。我確實懂得如何對自定義類進行編碼,但無法弄清楚如何爲已經由iOS定義的對象執行此操作。
我知道在Objective-C上有一個答案,但真的很喜歡Swift解決方案。謝謝。
PS我試圖繼承MKMapItem並提供「新」初始值設定項,即使這需要在其他地方進行大量的代碼更改。但是,這導致「不能分配給財產:'地標'是一個只能得到的財產」。 「地標」和「isCurrentLocation」都是隻讀的。
import UIKit
import MapKit
class NewMapItem: MKMapItem {
required init(placemark: MKPlacemark, isCurrentLocation:Bool, name: String, phoneNumber: String, url: URL, timeZone: TimeZone) {
self.placemark = placemark //compiler complains "get-only"
self.isCurrentLocation = isCurrentLocation //compiler complains "get-only"
self.name = name
self.phoneNumber = phoneNumber
self.url = url
self.timeZone = timeZone
}
// MARK: NSCoding
init?(coder decoder: NSCoder) {
placemark = (decoder.decodeObject(forKey: "placemark") as! MKPlacemark?)! //compiler complains "get-only"
isCurrentLocation = decoder.decodeBool(forKey: "isCurrentLocation") //compiler complains "get-only"
name = decoder.decodeObject(forKey: "name") as? String
phoneNumber = decoder.decodeObject(forKey: "phoneNumber") as? String
url = decoder.decodeObject(forKey: "url") as! URL?
timeZone = decoder.decodeObject(forKey: "timeZone") as! TimeZone?
}
func encode(with coder: NSCoder) {
coder.encode(placemark, forKey: "placemark")
coder.encode(isCurrentLocation, forKey: "isCurrentLocation")
coder.encode(name, forKey: "name")
coder.encode(phoneNumber, forKey: "phoneNumber")
coder.encode(url, forKey: "url")
coder.encode(timeZone, forKey: "timeZone")
}
}