繁体   English   中英

SWIFT中的KVO测试

[英]KVO test in SWIFT

我已经在Swift中为纬度/经度编写了一个类,并且希望将Location放置在视图控制器上。 我正在将KVO用作MVC的一部分。 我目前正在试用,但为什么不

 func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    let location = locations.last as! CLLocation
    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, e) -> Void in
        if let error = e {
            println("Error:  (e.localizedDescription)")
        } else {
            let placemark = placemarks.last as! CLPlacemark
            LocationClass.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)
            self.LocationManager.stopUpdatingLocation()
            self.LocationString = "\(placemark.subLocality), \(placemark.locality)"
        }
    })



}


override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) {
            println("Things have changed")
    }
}

但是为什么不'observeValueForKeyPath函数被调用? 任何想法都很棒。 LocationString是类顶部的动态变量。 MyContext只是一个var int = 0

您正在将观察者附加到Class对象。 假设您的“自我”是LocationClass的实例,并且具有“ LocaionString”属性,则应为

self.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)

并且不要忘记附加“动态”修饰符

首先,您要分配值,将自身添加为观察者。 注册观察该变量后,该值永远不会更改。

self.LocationString = "\(placemark.subLocality), \(placemark.locality)"
                    //println(LocationString)

LocationClass.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)/

它应该以不同的顺序:

LocationClass.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)/
self.LocationString = "\(placemark.subLocality), \(placemark.locality)"
                    //println(LocationString)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM