2015-04-27 4 views
2

Я пытаюсь перебрать с адреса ячейки tableView в mapView и показать вывод на карте.mapView.addAnnotation() говорит: «неожиданно найдено нуль при распаковке необязательного значения»

Я уверен, что в моем коде все не ноль.

Но Xcode говорит, что мой oldValue является nil (in didSet{}). Я не знаю, как это исправить.

Ниже мой код:

class MapViewController: UIViewController, MKMapViewDelegate { 

    @IBOutlet weak var mapView: MKMapView! { 
     didSet { 
      mapView.mapType = .Standard 
      mapView.delegate = self 
     } 
    } 


    var location:CLLocation? { 
     didSet { 
      clearWayPoints() 
      if location != nil { 
       println(location!.coordinate.longitude) 
       let coordinate = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) 
       let pin = MapPin(coordinate: coordinate, title: "Current", subtitle: "here") 
       setAnnotation(pin) 
      } 
     } 
    } 

    private func clearWayPoints() { 
     if mapView?.annotations != nil { 
      mapView.removeAnnotations(mapView.annotations as [MKAnnotation]) 
     } 
    } 

    func setAnnotation(pin: MKAnnotation) {   
     mapView.addAnnotation(pin) 
     mapView.showAnnotations([pin], animated: true) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
    } 

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { 
     var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.AnnotationViewReuseIdentifier) 
     if view == nil { 
      view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.AnnotationViewReuseIdentifier) 
      view.canShowCallout = true 
     } else { 
      view.annotation = annotation 
     } 
     return view 

    } 

    struct Constants { 
     static let AnnotationViewReuseIdentifier = "map cell" 
    } 
} 

Моя модель просто var location:CLLocation?, и я обновлю это значение из моего Segue.

Я уверен, что получаю правильную координату в println().

Но Xcode всегда говорит

fatal error: unexpectedly found nil while unwrapping an Optional value

И я нашел nil, кажется oldValue=(CLLocation?)nil!

Ниже мой простой класс, который реализует MapPinMKAnnotation

class MapPin: NSObject, MKAnnotation { 
    var coordinate: CLLocationCoordinate2D 
    var title: String? 
    var subtitle: String? 

    init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) { 
     self.coordinate = coordinate 
     self.title = title 
     self.subtitle = subtitle 
    } 
} 

ответ

5

Я просто имел точно такую ​​же проблему и установил ее! Вы пытаетесь добавить аннотацию к mapView, которая еще не инициализирована.

Проблема в том, что вы устанавливаете location в prepareForSegue:. На данный момент ваш mapView равен нулю. Позвоните по телефону mapView.addAnnotation: в viewDidLoad:, чтобы исправить это.

Я думаю, именно поэтому он говорит: «Сделайте любую дополнительную настройку после, загружая представление». потому что тогда все ваши выходы инициализируются.

Надеюсь, это поможет!

Смежные вопросы

 Смежные вопросы