我在 Swift 中为 Lat/Long 编写了一个类,我想将 Location 放在 View Controller 上。我正在使用 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
最佳答案
您正在将观察者附加到类对象。假设您的“self”是 LocationClass 的实例并具有“LocaionString”属性,它应该是
self.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)
并且不要忘记附加“动态”修饰符
关于ios - SWIFT 中的 KVO 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30235506/