如何从swift 3中的核心数据属性(列)中删除特定数据

时间:2017-12-05 11:00:27

标签: ios swift database

我在Swift 3中做核心数据。我能够存储数据并且能够获取,工作正常。但是,在尝试删除特定数据时,假设字符串数据,它无法做到。

以下是我的代码

        //Delete if existing data there
        let context = DatabaseController.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UserData")
        fetchRequest.predicate = NSPredicate.init(format: "userFocusData==\(node.label.text!)")

        let result = try? context.fetch(fetchRequest)
        let resultData = result as! [UserData]

        for object in resultData {
            context.delete(object)
        }

        do {
            try context.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
            self.showAlert(message: "Data not able to save, please try again later.", title: kText_AppName)
        } catch {

        }

它在下一行崩溃

        let result = try? context.fetch(fetchRequest)

崩溃报告

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath Sharepoint not found in entity <NSSQLEntity UserData id=6>'

但是,我传递了一些字符串,我希望从数据库中删除该字符串。 任何人都可以建议我,如何解决这个问题,我没有很好地使用核心数据。

2 个答案:

答案 0 :(得分:1)

在Swift 3中
在此代码中,我将基于id

删除数据
func deleteTrip(Id:String)
    {
        managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"your entity")
        fetchRequest.predicate = NSPredicate(format: "id = %@", "\(Id)")
        do
        {
            let fetchedResults =  try managedContext!.fetch(fetchRequest) as? [NSManagedObject]

            for entity in fetchedResults! {

                managedContext?.delete(entity)
                do
                {
                    try managedContext.save()



                }


                catch let error as Error!
                {
                    print(error.localizedDescription)
                }


            }
        }
        catch _ {
            print("Could not delete")

        }
    }

答案 1 :(得分:0)

发现问题。

所以,解决方案的答案是

fetchRequest.predicate = NSPredicate(format: "UserData.userFocusData = %@",node.label.text!)