且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Swift中清空并保存核心数据表的最简单方法是什么?

更新时间:2023-11-28 22:41:58

一种解决方案是获取对象并将其删除。
这是一个示例(请确保您指定了自己的实体):

One solution is to fetch the objects and delete them. Here is an example (make sure you specify your own entity) :

// If you'll be using the Managed Object Contexte often,
// you might want to make it a lazy property :
lazy var managedObjectContext : NSManagedObjectContext? = {
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    if let managedObjectContext = appDelegate.managedObjectContext {
        return managedObjectContext
    }
    else {
        return nil
    }
}()

func deleteData() {
    let context = self.managedObjectContext!

    let fetchRequest = NSFetchRequest(entityName: "yourEntity")
    fetchRequest.includesPropertyValues = false // Only fetch the managedObjectID (not the full object structure)
    if let fetchResults = context.executeFetchRequest(fetchRequest, error: nil) as? [yourEntity] {

        for result in fetchResults {
            context.deleteObject(result)
        }

    }

    var err: NSError?
    if !context.save(&err) {
        println("deleteData - Error : \(err!.localizedDescription)")
        abort()
    } else {
        println("deleteData - Success")
    }
}