NSUserDefaults 和使用 setobject 方法在 Swift 中存储 CLLocationCoordinate2D 错误
NSUserDefaults and using setobject method to store CLLocationCoordinate2D error in Swift
我在这里找到了这个问题的答案:Store CLLocationCoordinate2D to NSUserDefaults。而且代码写在Objective C。在大多数情况下,我了解 link 中的代码发生了什么。但是,我很难将语法翻译成 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 代码一样。
我在这里找到了这个问题的答案:Store CLLocationCoordinate2D to NSUserDefaults。而且代码写在Objective C。在大多数情况下,我了解 link 中的代码发生了什么。但是,我很难将语法翻译成 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
中(而不是 SwiftDictionary
)。 - 已将此
NSDictionary
传递给您的NSUserDefaults
,现在应该接受它,就像 Objective-C 代码一样。