删除核心数据项

时间:2016-09-24 12:49:58

标签: ios swift core-data

如何删除实体中特定属性中的所有数据我不想清空实体中的所有属性这是我现在拥有的删除实体中所有属性的内容

 func deletObject(){
    let fetchRequest = NSFetchRequest()
    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    fetchRequest.includesPropertyValues = false
    let context:NSManagedObjectContext = appDel.managedObjectContext
    let moc = context
    fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: moc)

    do {
        if let results = try moc.executeFetchRequest(fetchRequest) as? [NSManagedObject] {
            for result in results {
                moc.deleteObject(result)
            }
            try moc.save()
            self.cart = [Cart]()
            self.tableView.reloadData()
            totalAmouLa.text = "₦\(Int(totalHoursWorkedSum))"
        }
    } catch {
        print("FAILED")
    }

}

修改 我想删除delivery实体中的Cart Image

1 个答案:

答案 0 :(得分:1)

您无法从核心数据模型删除属性,只能重置该值。

executeFetchRequest成功时返回保证[Cart],可选绑定永远不会失败

func deletObject(){
    let fetchRequest = NSFetchRequest()
    let appDel  = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext
    fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)

    do {
        let results = try context.executeFetchRequest(fetchRequest) as! [Cart]
        results.forEach { $0.delivery = 0.0 }
        try context.save()
        self.tableView.reloadData()
        totalAmouLa.text = "₦\(Int(totalHoursWorkedSum))"
    } catch {
        print("FAILED")
    }
}