简体   繁体   English

NSUserDefaults并使用setobject方法在Swift中存储CLLocationCoordinate2D错误

[英]NSUserDefaults and using setobject method to store CLLocationCoordinate2D error in Swift

I found the answer to this question here: Store CLLocationCoordinate2D to NSUserDefaults . 我在这里找到了此问题的答案:将CLLocationCoordinate2D存储到NSUserDefaults And the code is written in Objective C. I understand, for the most part, what is happening with the code in that link. 代码是用目标C编写的。在大多数情况下,我了解该链接中的代码正在发生什么。 However, it is difficult for me to translate the syntax over to Swift. 但是,我很难将语法转换为Swift。 And I think it would be helpful for others to have this translation as well. 而且,我认为对其他人也进行翻译也很有帮助。

Just to reiterate the error, it is: Cannot invoke 'setObject' with an argument list of type (CLLocationCoordinate2D, forKey: String!) . 只是要重申该错误,它是: Cannot invoke 'setObject' with an argument list of type (CLLocationCoordinate2D, forKey: String!) And here is the syntax that is causing this problem: 这是导致此问题的语法:

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()

Just change your code to the following 只需将代码更改为以下内容

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()

What I've done is: 我所做的是:

  • Create two NSNumber objects with the Double s and collected them in an NSDictionary (and not a Swift Dictionary ). 使用Double创建两个NSNumber对象,并将它们收集在NSDictionary (而不是Swift Dictionary )。
  • Passed this NSDictionary to be saved by your NSUserDefaults , which should accept it now, just like the Objective-C code. 将此NSDictionary传递给您的NSUserDefaults保存,它现在应该接受它,就像Objective-C代码一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM