0

I have written a class in Swift for Lat/Long and I want to place the Location on the view controller. I am using KVO as a part of MVC. I am just trialing at the moment but why doesn't

 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")
    }
}

but why doesn't 'observeValueForKeyPath function get called ? Any ideas would be great. LocationString is a dynamic var at the top of the class. MyContext is just a var int = 0

Jason
  • 1,057
  • 3
  • 13
  • 31

2 Answers2

1

You are attaching observer to Class object. Assuming your 'self' is instance of LocationClass and has 'LocaionString' property, it should be

self.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)

and don't forget attach 'dynamic' modifier

Satachito
  • 5,838
  • 36
  • 43
0

You're first assigning the value, the adding self as observer. The value never changes AFTER you've registered to observe that variable.

self.LocationString = "\(placemark.subLocality), \(placemark.locality)"
                    //println(LocationString)

LocationClass.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)/

It should be in different order:

LocationClass.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)/
self.LocationString = "\(placemark.subLocality), \(placemark.locality)"
                    //println(LocationString)
Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76
  • thanks for that, but it still doesn't work.. I have amended my code in my description, thanks – Jason May 14 '15 at 11:05