ios - 观察另一个类属性

标签 ios swift key-value-observing

我有一个管理应用中位置的单例类:

import UIKit
import CoreLocation

class Location: NSObject, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var currentLocation:CLLocationCoordinate2D? {
        didSet {
            self.locationManager.stopUpdatingLocation()
        }
    }

    //////////////////////////////////////////////////////////////////////////////
    class var manager: Location {
        return UserLocation
    }


    //////////////////////////////////////////////////////////////////////////////
    override init () {
        super.init()

        if self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {
            self.locationManager.requestWhenInUseAuthorization()
        }
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.distanceFilter = 50


    }


    //////////////////////////////////////////////////////////////////////////////
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if self.currentLocation == nil {
            print("User Location NOT Updated.")
        } else {
            print("did update location")
        }
        self.currentLocation = manager.location!.coordinate

    }


    //////////////////////////////////////////////////////////////////////////////
    func startLocationUpdate() {
        self.locationManager.startUpdatingLocation()
    }


    //////////////////////////////////////////////////////////////////////////////
    func stopLocationUpdate() {
        self.locationManager.stopUpdatingLocation()
    }

}

// Mark: - Singleton Location
//////////////////////////////////////////////////////////////////////////////
let UserLocation = Location()

所以我可以从任何其他类(class)打电话:

    let theCurrentLocation = UserLocation.currentLocation

但是是否可以在另一个类中为该属性添加一些观察者?

是否可以通过其他巧妙的方式通知另一个类属性已更改?

我找到了 addObserver方法,addObserver(observer: NSObject, forKeyPath: String, options: NSKeyValueObservingOptions, context: UnsafeMutablePointer<Void>)但不确定是否可以在这种情况下使用。我在找这样的东西?

class AnotherCLass: NSObject {
    override init() {
        super.init()

        // seudo ->
        UserLocation.addObserver(self, UserLocation.currentLocation, "someAction:")
    }

    func someAction() {
        print("currect location has changed..")
    }

}

编辑:

所以我看了一下Key-Value Observing ,这听起来正是我所需要的。我遵循了指南,但是当我想要观察的属性发生更改时,我没有收到任何通知。所以我这样添加观察者:

UserLocation.addObserver(self, forKeyPath: "currentLocation", options: .New, context: nil)

观察方法是这样的:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    print("notification received")
    if keyPath == "currentLocation" {
        print("Current Location received")   
    }
}

但是这个方法永远不会被调用,即使'currentLocation'被改变了...

最佳答案

var currentLocation 更改为 dynamic var currentLocation。您必须将动态修饰符添加到您想要在 KVO 中观察的任何属性。

关于ios - 观察另一个类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34654909/

相关文章:

ios - 如何在 iOS Swift4 中滚动时增加/减小 UILabel 字体大小以及宽度和高度

ios - 设置属性导致 EXC_BAD_ACCESS 崩溃(CLLocationManager Singleton)

objective-c - KVO 通过 NSArrayController 添加/删除对象

ios - 当我从 Scheme Url 启动应用程序时未调用 openUrl

swift - POST 请求未在 Swift 中发送

ios - 如何在 MSMessage 中嵌入 URL?

ios - 为什么 KVO 在新旧值相同时发送更改通知?

ios - WebView 不显示我的 html 文件

ios - 添加 iOS @1x、@2x、@3x PER 设备,如何?

iOS - 当键盘显示时顶部单元格向上移动远离屏幕