在初始化之前使用的变量

时间:2015-04-25 09:53:08

标签: swift

我已经编写了下面的代码并且总是收到错误

(1)初始化之前使用的变量self.pointOnMap。

(2)在初始化之前由闭包捕获的变量self.pointOnMap。

我不明白为什么,因为我已经声明了self.pointOnMap = MKPointAnnotation(),它应该尽早初始化它。

class Pin: NSManagedObject {
    var mapView: MKMapView?
    var pointOnMap: MKPointAnnotation?

    @NSManaged var lat: Double
    @NSManaged var lon: Double
    @NSManaged var photos: Photo?

    override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
        super.init(entity: entity, insertIntoManagedObjectContext: context)
        self.pointOnMap = MKPointAnnotation()
    }

    init(dictionary: [String : AnyObject], context: NSManagedObjectContext) {
        let entity = NSEntityDescription.entityForName("Pin", inManagedObjectContext: context)!
        super.init(entity: entity, insertIntoManagedObjectContext: context)

        lat = 1.0
        lon = 2.0

        self.pointOnMap = MKPointAnnotation()
        println(self.pointOnMap) // RETURNS ERROR (1)
        self.pointOnMap!.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon) // RETURNS ERROR (2)
    }

1 个答案:

答案 0 :(得分:0)

我无法重现您的设置,因此我无法使用您的确切示例进行测试,但我认为您应该使用便利初始化程序和self.init,如下所示:

class Pin: NSManagedObject {
    var mapView: MKMapView?
    var pointOnMap: MKPointAnnotation?
    @NSManaged var lat: Double
    @NSManaged var lon: Double
    @NSManaged var photos: Photo?

    override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
        super.init(entity: entity, insertIntoManagedObjectContext: context)
        self.pointOnMap = MKPointAnnotation()
    }

    // Replace `init` with `convenience init`
    convenience init(dictionary: [String : AnyObject], context: NSManagedObjectContext) {

        let entity = NSEntityDescription.entityForName("Pin", inManagedObjectContext: context)!

        // Call the overriding init with `self.init(...)` instead of `super.init(...)`
        self.init(entity: entity, insertIntoManagedObjectContext: context)

        // Now, self.pointOnMap has the value declared by `override init`

        lat = 1.0
        lon = 2.0

        self.pointOnMap = MKPointAnnotation()
        println(self.pointOnMap)
        self.pointOnMap!.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
    }
}

查看“行动中的指定和便利初始化程序”in this page,我认为它涵盖了您的情况。