-2

My code below deletes a string from the index via delete button. However it is not delete from the core data set. If view is refreshed all items in the set are still there. All I want is when the user hits the delete func that that string is deleted forever. This is a download link to my code https://www.dropbox.com/s/m5fpiilksye4pru/photo2.zip?dl=0

 var users = [Item]()
class cell: UICollectionViewCell {
    var delegateA: datacollectionProfotocol?
    var index : IndexPath?
    @IBOutlet var name : UILabel!
    @IBAction func show() {

    }
    @IBAction func delete() {
       delegateA?.deleteData(indx: (index?.row)!)
    }
}

protocol datacollectionProfotocol {

func deleteData(indx:Int)
}
extension ViewController : datacollectionProfotocol {


func deleteData(indx: Int) {
    users.remove(at: indx)
    block.reloadData()
}
  • can you explain this line All I want is when the user hits the delete func that that string is deleted forever – Nazmul Hasan Aug 16 '19 at 03:00
  • When I hit the delete button it does not delete the item from the index it only hides it. When I refresh the view the item is still there. So say set = {a,e,c}. I delete e the set should only be {a,c}. Right now my code is not deleting e. –  Aug 16 '19 at 03:04
  • your example code not working my mac – Nazmul Hasan Aug 16 '19 at 03:31

1 Answers1

1

You have to delete the item also from the Core Data stack (context is the NSManagedObjectContext instance)

func deleteData(indx: Int) {
    let userToRemove = users.remove(at: indx)
    context.delete(userToRemove)
    do {
        try context.save()
        block.reloadData()
    } catch { print(error) }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • And whenever you make changes to a Core Data `ManagedObjectContext`, you have to **save** your context to apply the changes made. This answer's already got it in it, I just wanted to emphasize it. – emmics Aug 16 '19 at 05:02
  • I tried to do exactly what you coded. Its not working I updated my link. Could you look at the link? –  Aug 24 '19 at 00:30