我正在尝试将自己的属性添加到MKAnnotation,但我这样做的方法却出错了。我想要完成的是添加title
和subtitle
,例如height
和rate
。
class MapPin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String
var subtitle: String
var imageName: String
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String, imageName: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
self.imageName = imageName
}
}
这是我定义标记的方式:
var request = NSURLRequest(URL: url!)
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
if data != nil {
var dataArray = JSON(data: data!)
for (key, data) in dataArray {
var title = data["name"]
var subtitle = data["description"]
var lat = data["lat"]
var lng = data["lng"]
var marker = CustomPointAnnotation()
marker.coordinate = CLLocationCoordinate2D(latitude: lat.doubleValue, longitude: lng.doubleValue)
marker.title = title.string
marker.subtitle = subtitle.string
marker.imageName = "marker.png"
marker.image = "Test";
mapView.addAnnotation(marker)
}
}
这是我尝试检索数据的地方:
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
println("Called")
performSegueWithIdentifier("mapToCity", sender: self)
var pinData = view.annotation as! MapPin //EXC_BAD_ACCESS Error
var title = pinData.title
var subtitle = pinData.subtitle
var lat = pinData.coordinate.latitude
var lng = pinData.coordinate.longitude
var image = pinData.imageName
NSUserDefaults.standardUserDefaults().setObject(title, forKey: "title")
NSUserDefaults.standardUserDefaults().setObject(subtitle, forKey: "subtitle")
NSUserDefaults.standardUserDefaults().setObject(lat, forKey: "lat")
NSUserDefaults.standardUserDefaults().setObject(lng, forKey: "lng")
}
当我尝试执行它时,我在Thread 1: EXC_BAD_ACCESS (code =1, address=0x4)
行上收到错误var pinData
。可能是什么原因以及如何解决?
答案 0 :(得分:0)
首先,您需要检查您获得的注释类型:
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
println("Called")
// Below condition is for custom annotation
let MapPin= view.annotation as? MapPin
println("Subtitle \(MapPin.subtitle)")
performSegueWithIdentifier("mapToCity", sender: self)
var title = MapPin.title
var subtitle = MapPin.subtitle
var lat = MapPin.coordinate.latitude
var lng = MapPin.coordinate.longitude
var image = MapPin.imageName
NSUserDefaults.standardUserDefaults().setObject(title, forKey: "title")
NSUserDefaults.standardUserDefaults().setObject(subtitle, forKey: "subtitle")
NSUserDefaults.standardUserDefaults().setObject(lat, forKey: "lat")
NSUserDefaults.standardUserDefaults().setObject(lng, forKey: "lng")
}else{
return nil
}
}