簡體   English   中英

Swift 3:如何在按下 UI 按鈕時刪除 Core Data 中的單個記錄

[英]Swift 3: How to delete the single record in the Core Data when a UIbutton is Pressed

我有一個功能,我可以將配置文件添加到收藏夾列表(通過核心數據保存),當我想將其標記為“不喜歡”時,它應該從核心數據和表列表視圖(收藏夾視圖控制器)中刪除)。

到目前為止,我擁有的代碼從列表中刪除所有記錄,而不是刪除特定記錄。

請在下面找到代碼:-

 @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,當我再次重新啟動應用程序時:

在此處輸入圖片說明

我試圖將第二個配置文件標記為不喜歡,它不會更新 tableview。 當我重新啟動應用程序時,它顯示“標簽”

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
    let predicate = NSPredicate(format: "profileID == %@", id as CVarArg)
    fetchRequest.predicate = predicate
    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)")
    }

對 profileID 使用謂詞。

let predicate = NSPredicate(format: "name == %@ AND type == %@", "your target name","your target type")
            var fetchedEntities = [TrackTable]()
            let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "TrackTable")
            fetchRequest.predicate = predicate
            do {
                    fetchedEntities = try! managedContext?.fetch(fetchRequest) as! [TrackTable]
                    for sequence in fetchedEntities
                    {
                        managedContext?.delete(sequence)
                    }
                    catch
                    {

                    }
     }

在上面的謂詞nametype是您要刪除特定實體的表實體。

* Add a Predicate Like given below to search for a particular item from the list of Favourites using it's unique profile Id. Search for that item in it's entity and delete that item from core data.
*****************************************
let predicateFavs = NSPredicate(format: “profileID = %@", String(describing: id!))
    let favList = CoreDataHandler.sharedInstance.fetchEntityWithName(“FavProfile”, predicate: predicateFavs) as! [FavProfile]

    context.performAndWait({
    for object in favList{
    self.context.delete(object)
    }

    do {
    try self.context.save()

    } catch {
    print("error : \(error)")
    }
    })


********************************************   



    func fetchEntityWithName(_ entityName : NSString, predicate: NSPredicate) -> NSArray{

        // Create Entity Description
        let entityDescription = NSEntityDescription.entity(forEntityName: entityName as String, in: context)
        // Initialize Fetch Request
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
        // Configure Fetch Request
        fetchRequest.entity = entityDescription
        fetchRequest.predicate = predicate
        var result = NSArray()
        do {
            result = try context.fetch(fetchRequest) as NSArray
            print(result)

        } catch {
            let fetchError = error as NSError
            print(fetchError)
        }

        return result
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM