我有一个管理应用中位置的单例类:
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/