【发布时间】:2017-05-14 20:33:39
【问题描述】:
我想将位置坐标保存到核心数据中——存储和检索它们的正确方法是什么?
目前我正在这样做并遇到错误:
var newPlaceCoordinate = CLLocationCoordinate2D()
var newPlaceLatitude = CLLocationDegrees()
var newPlaceLongitude = CLLocationDegrees()
我通过 Google 地图 API 使用自动完成小部件获取我的坐标。
let newPlaceCoordinate = place.coordinate
self.newPlaceCoordinate = place.coordinate
let newPlaceLatitude = place.coordinate.latitude
print(newPlaceLatitude)
self.newPlaceLatitude = place.coordinate.latitude
let newPlaceLongitude = place.coordinate.longitude
print(newPlaceLongitude)
self.newPlaceLongitude = place.coordinate.longitude
然后存储我使用的坐标:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newPlace = NSEntityDescription.insertNewObject(forEntityName: "StoredPlace", into: context)
newPlace.setValue(newPlaceCoordinate, forKey: "coordinate")
newPlace.setValue(newPlaceLatitude, forKeyPath: "latitude")
newPlace.setValue(newPlaceLongitude, forKeyPath: "longitude")
我将属性全部设置为字符串类型。 然后检索我的 ViewDidLoad 我有:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "StoredPlace")
request.returnsObjectsAsFaults = false
if let coordinate = result.value(forKey: "coordinate") as? String
{
let latitude = (coordinate as NSString).doubleValue
let longitude = (coordinate as NSString).doubleValue
let markers = GMSMarker()
markers.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
markers.icon = GMSMarker.markerImage(with: UIColor.yellow)
markers.tracksViewChanges = true
markers.map = vwGMap
}
所以这不起作用并产生'attribute:property =“coordinate”的错误;所需类型 = NSString;给定类型 = NSConcreteValue'。我有几个问题。
如何正确保存坐标数据? 我是否将其保存为 CLLocationDegrees 或 CLLocationCoordinate2D? 如何将这些对象转换为 NSString 或者我应该在我的属性中使用不同的类型? (我尝试将其更改为 Double 或 Integer 但它也产生了错误)。我有多个位置坐标,我想从核心数据中存储和检索。
【问题讨论】:
标签: ios swift core-data nsstring cllocation