为什么使用Convenience Initializer修复我的问题?

时间:2017-10-06 12:56:05

标签: swift mapkit

请查看Renderer类的两个版本。 Renderer1的初始化程序成功执行。 Renderer2的初始化程序在对super.init的调用时崩溃。崩溃消息中引用的init(overlay :)初始化程序由MKOverlayRenderer声明,它是类层次结构的3级。

import UIKit
import MapKit

class ViewController: UIViewController {

    class Renderer1 : MKPolylineRenderer {

         convenience init(polyline: MKPolyline, lineWidth: CGFloat) {
             self.init(polyline: polyline)
             self.lineWidth = lineWidth
         }
    }

    class Renderer2 : MKPolylineRenderer {

        // Crash Message:
        // /Users/Robert/Temp/Test/Test/ViewController.swift: 22: 11: fatal error: use of unimplemented initializer 'init(overlay:)' for class 'Test.Renderer2'
        // 2017-10-06 08:37:10.582531-0400 Test[2962:932545] /Users/Robert/Temp/Test/Test/ViewController.swift: 22: 11: fatal error: use of unimplemented initializer 'init(overlay:)' for class 'Test.Renderer2'

        init(polyline: MKPolyline, lineWidth: CGFloat) {
            super.init(polyline: polyline) // <= Crashes Here!
            self.lineWidth = lineWidth
        }
    }

    private var renderer1: Renderer1? = nil
    private var renderer2: Renderer2? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        var coordinates = [CLLocationCoordinate2D]()
        for latitude in 1 ... 10 {
            coordinates.append(CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: 0))
        }

        let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)

        renderer1 = Renderer1(polyline: polyline, lineWidth: 10)

        renderer2 = Renderer2(polyline: polyline, lineWidth: 10)
    }
}

请有人帮我理解这里发生的事情吗?

1 个答案:

答案 0 :(得分:0)

因为类初始值设定项是私有,所以您只能通过方便子类和初始化它。 https://developer.apple.com/documentation/mapkit/mkpolyline