如何在 CoreData 中保存位置
Posted
技术标签:
【中文标题】如何在 CoreData 中保存位置【英文标题】:How to save Location in CoreData 【发布时间】:2017-09-18 03:44:37 【问题描述】:当长按手势被识别时,我正在尝试在 ios CoreData 中保存一个标记的位置。每当我调用手势时,应用程序总是崩溃。我还将这两个的 coreData 类型设置为 Double。由于我对iOS开发还不是很熟悉,如何以最简单的方式将坐标安全地存储在coreData中。
@IBAction func saveLocation(_ sender: Any)
guard let longPress = sender as? UILongPressGestureRecognizer else
return
if longPress.state == .ended
let touchLocation = longPress.location(in: mapView)
let coordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newLocation = NSEntityDescription.insertNewObject(forEntityName: "GeoData", into: context)
newLocation.setValue(coordinate.latitude as Double, forKey: "myLatitude")
newLocation.setValue(coordinate.longitude as Double, forKey: "myLongitude")
do
try context.save()
catch
//ERROR
【问题讨论】:
什么是崩溃日志? 对不起,我想这可能只是我的愚蠢。我一定是刚刚输入了一个我没有注意到的断点。看来它保存正确。 【参考方案1】:我创建了一个长按手势并将位置存储到这样的核心数据中--
创建一个长按手势并在核心数据中保存位置。
let longGesture = UILongPressGestureRecognizer(target: self, action:
#selector(longTap(_:)))
mapView.addGestureRecognizer(longGesture)
func longTap(_ sender: UIGestureRecognizer)
print("Long tap")
if sender.state == .ended
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
let touchLocation = sender.location(in: mapView)
let coordinate = mapView.convert(touchLocation,
toCoordinateFrom: mapView)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newLocation =
NSEntityDescription.insertNewObject(forEntityName: "GeoData", into:
context)
newLocation.setValue(coordinate.latitude as Double, forKey:
"myLatitude")
newLocation.setValue(coordinate.longitude as Double, forKey:
"myLongitude")
do
try context.save()
catch
//ERROR
print(error)
else if sender.state == .began
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
【讨论】:
以上是关于如何在 CoreData 中保存位置的主要内容,如果未能解决你的问题,请参考以下文章