mapView.addAnnotation()表示"在展开Optional值时意外发现nil"

Jam*_* Fu 2 null mkmapview mkannotation ios swift

我尝试从tableView单元格的地址转换为mapView并在地图上显示引脚.

我确信我的代码中的所有内容都不是零.

但Xcode说我的oldValuenil(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"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的模型就是var location:CLLocation?,我从我的segue更新了这个值.

我确信我在println()中得到了正确的坐标.

但Xcode总是说

致命错误:在展开Optional值时意外发现nil

我发现nil似乎是oldValue=(CLLocation?)nil!

以下是我MapPin实现的简单类MKAnnotation

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
    }
}
Run Code Online (Sandbox Code Playgroud)

chi*_*ger 5

我刚刚遇到了完全相同的问题并修复了它!您正在尝试将注释添加到mapView尚未初始化的注释中.

问题是,你设置locationprepareForSegue:.此时你的mapView是零.通话mapView.addAnnotation:viewDidLoad:解决它.

我想这就是为什么它说" 加载视图做任何额外的设置".因为那时你的所有商店都被初始化了.

希望这可以帮助!