ios - SWIFT 中的 KVO 测试

标签 ios swift key-value-observing

我在 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/

相关文章:

swift - Swift 中 "Just"库的文本输出

c - 如何从 Swift 调用标准 C 库?

json - Alamofire 响应在 JSON 内容与 SwiftyJSON 一起使用之前包含文本

ios - 通过KVO观察数据库值的变化

objective-c - 我应该在自定义 setter 中使用 will/didSetValueForKey 吗?

ios - 观察属性或覆盖 setter 更好吗?

ios - 无法识别的选择器发送到实例 [UIView setRefreshControl :]

ios - 自定义 UITableViewCell。如何创建 UITableViewCell 如屏幕截图所示

ios - 为什么 iOS6 中的 UICollectionView 框架比我定义的要小?

php - 将文件同步到 iOS 设备保护使用 htaccess