Delete Data from Coredata Swift

后端 未结 8 1247
你的背包
你的背包 2020-12-05 00:51

In my tableViewController I have the following. And I am trying to get delete an item to work.

var myData: Array = []

override func tableV         


        
相关标签:
8条回答
  • 2020-12-05 01:29

    Not sure what your question is but you have to delete the object from the NSManagedObjectContext instance. So in your commitEditingStyle function:

    let moc = appDelegate.managedObjectContext // or something similar to get the managed object context
    moc.delete(data)  // your NSManagedObject
    
    0 讨论(0)
  • 2020-12-05 01:32

    Update on my coding issue with executing a delete of data in swift and coredata. This the code I ended up with that worked.

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
            switch editingStyle {
            case .Delete:
                // remove the deleted item from the model
                let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
                let context:NSManagedObjectContext = appDel.managedObjectContext!
                context.deleteObject(myData[indexPath.row] as NSManagedObject)
                myData.removeAtIndex(indexPath.row)
                context.save(nil)
    
               //tableView.reloadData()
                // remove the deleted item from the `UITableView`
                self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            default:
                return
    
            }
    }
    

    EDIT Above for Swift 2.2 and Xcode 7.3.1

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        switch editingStyle {
        case .Delete:
            // remove the deleted item from the model
            let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let context:NSManagedObjectContext = appDel.managedObjectContext
            context.deleteObject(myData[indexPath.row] )
            myData.removeAtIndex(indexPath.row)
            do {
                try context.save()
            } catch _ {
            }
    
            // remove the deleted item from the `UITableView`
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        default:
            return
        }
    }
    

    Also need was these two lines of code to be corrected.

        var myData: Array<AnyObject> = []
    let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
    
    0 讨论(0)
提交回复
热议问题