[英]NSUserDefaults and using setobject method to store CLLocationCoordinate2D error in Swift
我在这里找到了此问题的答案:将CLLocationCoordinate2D存储到NSUserDefaults 。 代码是用目标C编写的。在大多数情况下,我了解该链接中的代码正在发生什么。 但是,我很难将语法转换为Swift。 而且,我认为对其他人也进行翻译也很有帮助。
只是要重申该错误,它是: 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()
只需将代码更改为以下内容
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()
我所做的是:
Double
创建两个NSNumber
对象,并将它们收集在NSDictionary
(而不是Swift Dictionary
)。 NSDictionary
传递给您的NSUserDefaults
保存,它现在应该接受它,就像Objective-C代码一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.