简体   繁体   中英

NSUserDefaults and using setobject method to store CLLocationCoordinate2D error in Swift

I found the answer to this question here: Store CLLocationCoordinate2D to NSUserDefaults . And the code is written in Objective C. I understand, for the most part, what is happening with the code in that link. However, it is difficult for me to translate the syntax over to 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!) . 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 ).
  • Passed this NSDictionary to be saved by your NSUserDefaults , which should accept it now, just like the Objective-C code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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