我已经在Swift for Lat / Long中编写了一个类,我希望将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是类顶部的动态var。 MyContext只是一个var int = 0
答案 0 :(得分:1)
您正在将观察者附加到Class对象。假设你的'self'是LocationClass的实例并且具有'LocaionString'属性,它应该是
self.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)
并且不要忘记附加'动态'修饰符
答案 1 :(得分:0)
您首先分配值,将自我添加为观察者。在您注册观察该变量后,该值永远不会改变。
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)