Anilkumar iOS Developer
Anilkumar iOS Developer

Reputation: 3755

How to delete particular data from core data attribute (column) in swift 3

I am doing core data in Swift 3. I am able to store data and able to fetch, working fine. But, while trying to delete particular data suppose string data, its not able to do.

Following is my code

        //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 {

        }

And its getting crash at following line

        let result = try? context.fetch(fetchRequest)

And crash report is

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

But, I am passing some string, that string I want to delete from database. Can anyone suggest me, how to fix this, I have not used core data well.

Upvotes: 1

Views: 1551

Answers (2)

Amul4608
Amul4608

Reputation: 1448

In Swift 3
In this Code i am delete data based on 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")

        }
    }

Upvotes: 1

Anilkumar iOS Developer
Anilkumar iOS Developer

Reputation: 3755

Issue found.

So, the solution answer is

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

Upvotes: 0

Related Questions