我有一个带有自定义注释的地图视图。注释是从coreData加载的。我希望用户能够单击注释来编辑或删除图钉。 我真的很努力尝试仅删除所选的注释。我是编程新手,甚至是Core Data新手,所以请原谅。 这是我正在尝试执行的功能。使用此功能,不会删除或打印任何内容。
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!)
答案 0 :(得分:0)
我在扩展程序中全部使用此代码来工作。
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。如果有人有更简洁的设置方法,请告诉我!