我在这里找到了这个问题的答案:Store CLLocationCoordinate2D to NSUserDefaults。代码是用Objective 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()
答案 0 :(得分: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代码一样。