Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

swift - CoreData Clear and Attributes data in a tableView

I have looked around a lot and there doesn't seem to be a clear answer to this? I have a table view controller where when I delete the cell and want it to remove the data show in a second table view controller which it is linked to via segue. So when deleted the core data attribute shapes should be cleared. With the code below I can only get it to delete one key pair in the attribute and not all.

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        context!.delete(array[indexPath.row])
        array.remove(at: indexPath.row)
        let fetchRequest = NSFetchRequest<Notes>(entityName: "Notes")
        fetchRequest.predicate = NSPredicate(format: "shape = %@")
        saveList()
        do {
            let shapes = try context!.fetch(fetchRequest)
            for shape in shapes {
                context!.delete(shape)
                let managedObjectData:NSManagedObject = shape as NSManagedObject
                context!.delete(managedObjectData)
            }
            try context!.save()
        } catch _ {
            // error handling
        }
        tableView.reloadData()
    }
}

enter image description here enter image description here enter image description here

Is there a simple way to clear an attribute of all its data?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, the fastest and correct way to achieve this is by using Coredata deletion rules. I guess in CoreData model you have a one to many relations - each color is related to some shape. Therefore, in the Coredata editor go on the Identity Inspector and set the relation's delete rule to cascade. This means that once you delete a color, all of its corresponding shapes will be automatically deleted from the Perstistence store, no need to manually deleting them by looping over them!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...