gpt4 book ai didi

swift - 从使用 CoreData 创建的 mapView 中删除图钉

转载 作者:行者123 更新时间:2023-11-30 11:11:01 24 4
gpt4 key购买 nike

我有一个带有自定义注释的 map View 。注释是从 coreData 加载的。我希望用户能够单击注释来编辑或删除引脚。 我真的很难尝试仅删除选定的注释。我是编程新手,甚至是核心数据新手,所以请原谅我的无知。 这是我试图实现的功能。使用此功能不会删除或打印任何内容。

func  deletePin() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let requestDel = NSFetchRequest<NSFetchRequestResult>(entityName: "Fish")

let thisCatch = selectedAnnotation?.title
requestDel.returnsObjectsAsFaults = false

let predicateDel = NSPredicate(format: "species == %d", thisCatch!)
requestDel.predicate = predicateDel


do {
let locations = try context.fetch(requestDel)
for location in locations{
context.delete(location as! NSManagedObject)

self.map.removeAnnotation(selectedAnnotation!)
print("pinDeleted")
}
} catch {
print("Failed")
}

do {
try context.save()
} catch {
print("Failed saving")
}
}

这是我尝试调用deletePin()的扩展

extension MapViewController: ExampleCalloutViewDelegate {
func mapView(_ mapView: MKMapView, didTapDetailsButton button: UIButton, for annotation: MKAnnotation) {



let alert = UIAlertController(title: "Edit or Delete", message: "Any changes are permenate!", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

let deleteDataAction = UIAlertAction(title: "delete", style: .destructive, handler: { action in

self.deletePin()

// self.map.removeAnnotation(annotation)
// print(annotation.title!)

最佳答案

我在扩展中使用此代码使其正常工作。

extension MapViewController: ExampleCalloutViewDelegate {
func mapView(_ mapView: MKMapView, didTapDetailsButton button: UIButton, for annotation: MKAnnotation) {



let alert = UIAlertController(title: "Edit or Delete", message: "Any changes are permenate!", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

let deleteDataAction = UIAlertAction(title: "delete", style: .destructive, handler: { action in

let pinTitle = self.selectedAnnotation?.title

do{
let request: NSFetchRequest<Fish> = Fish.fetchRequest()
let predicate = NSPredicate(format: "species == %@", pinTitle!)
request.predicate = predicate

let locations = try self.context.fetch(request)
for location in locations{
self.context.delete(location)

self.map.removeAnnotation(self.selectedAnnotation!)
print("pinDeleted")
}
} catch {
print("Failed")
}

do {
try self.context.save()
} catch {
print("Failed saving")
}

})

就我而言,selectedAnnotation.title 是时间和日期,因此它是唯一的 ID 如果有人有更简洁的设置方法,请告诉我!

关于swift - 从使用 CoreData 创建的 mapView 中删除图钉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52174273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com