iOS:删除所有核心数据Swift

发布于 2021-01-31 23:44:33

对于如何迅速删除所有核心数据,我有些困惑。我创建了一个带有IBAction链接的按钮。单击按钮后,我将看到以下内容:

let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext

然后,我想出了各种方法来尝试删除所有核心数据内容,但似乎无法正常工作。我已经使用removeAll从存储的数组中删除,但是仍然不能从核心数据中删除。我假设我需要某种类型的for循环,但是不确定如何从请求中进行。

我尝试应用删除单行的基本原理

func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {

    let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
    let context:NSManagedObjectContext = appDel.managedObjectContext

    if editingStyle == UITableViewCellEditingStyle.Delete {

        if let tv = tblTasks {
            context.deleteObject(myList[indexPath!.row] as NSManagedObject)
            myList.removeAtIndex(indexPath!.row)
            tv.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
        }

        var error: NSError? = nil
        if !context.save(&error) {
            abort()
        }

    }

}

但是,这样做的问题是,当我单击按钮时,我没有indexPath值,而且还需要遍历所有似乎与上下文无关的值。

关注者
0
被浏览
93
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    我已经使用以下方法使其工作:

    @IBAction func btnDelTask_Click(sender: UIButton){
    
        let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext  
        let request = NSFetchRequest(entityName: "Food")
    
        myList = context.executeFetchRequest(request, error: nil)
    
    
        if let tv = tblTasks {
    
            var bas: NSManagedObject!
    
            for bas: AnyObject in myList
            {
               context.deleteObject(bas as NSManagedObject)
            }
    
            myList.removeAll(keepCapacity: false)
    
            tv.reloadData()
            context.save(nil)
        }
    }
    

    但是,我不确定这是否是执行此操作的最佳方法。我还收到一个“常数”推断为“有任何物体”的错误-因此,如果对此有任何解决方案,那就太好了

    编辑

    通过更改为bas进行修复:AnyObject



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看