2015-05-14 41 views
0

我在Lat/Long的Swift中編寫了一個類,我想將位置放在視圖控制器上。我正在使用KVO作爲MVC的一部分。我只是試運行的時刻,但爲什麼不SWIFT中的KVO測試

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

回答

0

你是第一次分配值,添加自我作爲觀察者。該值在您註冊後觀察該變量後永不改變。

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

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

應該在不同的順序:

LocationClass.addObserver(self, forKeyPath: "LocationString", options: .New, context: &self.myContext)/ 
self.LocationString = "\(placemark.subLocality), \(placemark.locality)" 
        //println(LocationString) 
+0

感謝的是,但它仍然無法正常工作..我在我的描述中修改了我的代碼,謝謝 – Jason

1

要附加觀察員Class對象。假設你的「自我」是LocationClass的實例,並且具有「LocaionString」屬性,它應該是

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

,不要忘記附上「動態」修改