2015-08-28 33 views
0

我在這裏找到了這個問題的答案:Store CLLocationCoordinate2D to NSUserDefaults。代碼是用Objective C編寫的。我大部分都理解該鏈接中的代碼發生了什麼。但是,我很難將語法翻譯成Swift。我認爲這對其他人也有幫助。NSUserDefaults和使用setobject方法來存儲Swift中的CLLocationCoordinate2D錯誤

只是爲了重申錯誤,它是:Cannot invoke 'setObject' with an argument list of type (CLLocationCoordinate2D, forKey: String!)。這裏是導致這一問題的語法:

let mapAnnotations = NSUserDefaults.standardUserDefaults() 
let newCoordinate = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView) 
var title: String! = "" 
self.mapAnnotations.setObject(newCoordinate, forKey: title) //the error is here 
self.mapAnnotations.synchronize() 
+0

閱讀有關'NSUserDefaults'的Apple文檔,它可以節省的東西有限制。 – zaph

+0

@ zaph我明白這是事實。但是,似乎這個鏈接:http://stackoverflow.com/questions/18910612/store-cllocationcoordinate2d-to-nsuserdefaults,提供了一種方法,您可以將CLLocationCoordinate2D存儲到NSUserDefaults中。我只是不知道從Objective C到Swift的翻譯。 – Jae

回答

0

只要你的代碼更改爲以下

let mapAnnotations = NSUserDefaults.standardUserDefaults() 
let newCoordinate = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView) 
let lat = NSNumber(double: newCoordinate.latitude) 
let lon = NSNumber(double: newCoordinate.longitude) 
let userLocation: NSDictionary = ["lat": lat, "long": lon] 
self.mapAnnotations.setObject(userLocation, forKey: "userLocation") //the error is here 
self.mapAnnotations.synchronize() 

我所做的是:

  • 創建兩個NSNumber對象Double並收集他們在NSDictionary(而不是Swift Dictionary)。
  • 通過這個NSDictionary被你的NSUserDefaults保存,現在應該接受它,就像Objective-C代碼一樣。
+0

謝謝你的幫助:) – Jae

相關問題