从核心数据中删除Swift 4

从核心数据中删除Swift 4,swift,core-data,Swift,Core Data,我有一个收藏夹按钮,当点击它时,会将特定角色的图像添加到CoreData中 @IBAction func favButtonClicked(_ sender: UIButton) { if sender.isSelected != true { saveFav() } } func saveFav() { let context = (UIApplication.shared.delegate as! AppDelegate).pers

我有一个收藏夹按钮,当点击它时,会将特定角色的图像添加到CoreData中

@IBAction func favButtonClicked(_ sender: UIButton) {
    if sender.isSelected != true {
        saveFav()
    }     
}   

func saveFav() {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let newFav = NSEntityDescription.insertNewObject(forEntityName: "Favorite", into: context)
    newFav.setValue((figure?.image)!, forKey: "favFig")

    do {
        try context.save()
        print("Saved!")
    } catch {
        //Process Error
    }
}

我的问题是,当再次单击按钮时,如何从CoreData中删除该图像?

在CoreData中,如果要删除它,每个对象都应该具有Id,如下所示

let fetchRequest: NSFetchRequest<Favorite> = Favorite.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "FavoriteID==\(ID)")

do {
    let objects = try context.fetch(fetchRequest)
    for object in objects {
        context.delete(object)
    }
    try context.save()
} catch _ {
    // error handling
}
let fetchRequest:NSFetchRequest=Favorite.fetchRequest()
fetchRequest.predicate=predicate.init(格式:“FavoriteID==\(ID)”)
做{
let objects=try context.fetch(fetchRequest)
对于对象中的对象{
context.delete(对象)
}
尝试context.save()
}接住{
//错误处理
}

是否有方法在单击按钮时添加ID?必须将FavoriteID添加到原始模型结构数据来自填充tableview和detail view控制器的JSON文件。单击FAV按钮将图像添加到唯一属性“favFig”下的CoreData。您需要添加另一个属性FavoriteIDOkay。那么,我应该为设置值设置什么呢?