【问题标题】:Swift 3: How to delete the single record in the Core Data when a UIbutton is PressedSwift 3:按下 UI 按钮时如何删除 Core Data 中的单个记录
【发布时间】: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


【解决方案1】:
    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 使用谓词。

【讨论】:

  • 它的工作并执行所需的功能。但是我觉得还是有一些小问题。当我将配置文件添加到收藏夹,然后当我将相同的配置文件标记为不喜欢时,我最喜欢的视图控制器仍然显示配置文件,直到我再次重新启动应用程序。当我重新启动应用程序时,配置文件名称从单元格中消失,而是名称更改为标签。请参考截图
  • 您应该在删除后从数据库中重新获取数据,然后重新加载tableview。试试看。
  • 我尝试了这个建议,但仍然无法重新加载表格视图
  • 如果可能的话,你能把文件给我吗?我会解决的。
  • 当然,我如何将文件发送给您?
【解决方案2】:
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 是您要删除特定实体的表实体。

【讨论】:

  • 我尝试了这个建议,但显然它给了我一些错误
【解决方案3】:
* 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
    }

【讨论】:

    猜你喜欢
    • 2018-01-06
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多