Jason
Jason

Reputation: 1067

KVO test in SWIFT

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

Upvotes: 0

Views: 409

Answers (2)

Satachito
Satachito

Reputation: 5888

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

Upvotes: 1

Lord Zsolt
Lord Zsolt

Reputation: 6557

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)

Upvotes: 0

Related Questions