gurkan stack
gurkan stack

Reputation: 225

Remove ONE row from Core Data Model Swift 3

I am using core data model to store data. I can add data programatically but removing a specific row is problem for me.

Song Model:

Song

in viewDidLoad to add a new data

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

//add a new data
let newSong = NSEntityDescription.insertNewObject(forEntityName: "Song", into: context)

newSong.setValue("turk_milleti_demokrattir", forKey: "path")
newSong.setValue("song1", forKey: "name")

do{
    try context.save() 
    print("success")

}
catch {
    print(error)
}

No problem in adding a new row. I want to remove specific row from Core Data Model. For example, suppose that I want to remove a song with named song1 . How can I remove song1 ?

If it was SQL, deleting a row from database would be like this:

DELETE FROM Song WHERE name='song1';

In core data - Swift 3, I am newbie. How can I remove specific row? In Swift 3 - Core Data ,What is equivalent of DELETE - WHERE statement in SQL?

Upvotes: 0

Views: 583

Answers (1)

Usama Sadiq
Usama Sadiq

Reputation: 609

I hope you have your model classes automatically created in your project please check the following code if this help

      let fetchRequest: NSFetchRequest<Song> = Song.fetchRequest()
        fetchRequest.predicate=NSPredicate(format: "name = %@", "song1")
        var fetchedItems = [Song]()
        do{
            fetchedItems=try context.fetch(fetchRequest)
        }catch{
            fatalError("Could not fetch")
        }
        for item in fetchedItems{
            context.delete(item)
        }
        context.save()

Upvotes: 2

Related Questions