【发布时间】:2018-01-02 15:18:07
【问题描述】:
我有一个功能,我可以将配置文件添加到收藏列表(通过核心数据保存),当我想将其标记为不收藏时,它应该从核心数据和 TableList 视图中删除(最喜欢的视图控制器)。
到目前为止,我的代码从列表中删除所有记录,而不是删除特定记录。
请在下面找到代码:-
@IBAction func saveFav(_ sender: UIButton) {
let propertyToCheck = sender.currentTitle!
var proID = saved_id
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = FavProfile(context: context)
switch propertyToCheck {
case "Add to Favourite":
// Link Task & Context
task.busName = bussinessName
task.profileID = Int32(id!)!
print ("saved id is: - \(task.profileID)")
print ("saved profile name is: - \(task.busName)")
fav_remove_fav_button_label.setTitle("Remove From Favourite", for: .normal)
// Save the data to coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()
let _ = navigationController?.popViewController(animated: true)
let alert = UIAlertController(title: "Alert", message: "Added to your Favourite list", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
case "Remove from Favourite":
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
let moc = getContext()
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [FavProfile]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
let alert = UIAlertController(title: "Alert", message: "Removed from your Favourite list", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
// self.favtable.tableView.reloadData()
default: break
}
}
我不知道我需要在这里修复什么,只删除特定记录。
感谢您的时间和精力。
屏幕 1,当我将个人资料标记为收藏时:
当我将同一个人资料标记为不喜欢时的屏幕 2:
屏幕 3,当我再次重新启动应用程序时:
我试图将第二个配置文件标记为不喜欢,它不会更新表格视图。当我重新启动应用程序时,它显示“标签”
【问题讨论】:
-
您已使用 for 循环删除所有获取的对象。您必须使用谓词仅获取相关对象,然后将其删除。
-
@PuneetSharma 我是 coredata 的新手,那么我们如何移除循环?
-
使用属性 profileID 获取特定的 FavProfile 实体,如果它是唯一的,然后从上下文中删除它。要了解如何使用 NSPredicate 获取特定实体,请阅读:developer.apple.com/library/content/documentation/Cocoa/…
标签: ios xcode core-data swift3