如何从Core Data中的持久存储中删除所有对象?

时间:2022-09-25 12:50:07

I have Core Data working in my app. So, I fetch an XML file, parse the data into model objects and insert them into core data. They are saved in the persistent store and I can access them when I relaunch the app. However, I want to be able to refresh the data in the persistent store at will, so I need to first remove existing objects from the store. Is there a straight-forward method for this?

我的核心数据在我的应用中运行。因此,我获取XML文件,将数据解析为模型对象并将其插入到核心数据中。它们保存在持久性存储中,我可以在重新启动应用程序时访问它们。但是,我希望能够随意刷新持久存储中的数据,因此我需要先从存储中删除现有对象。对此有直接的方法吗?

Thanks

谢谢


I found this solution:

我找到了这个解决方案

[managedObjectContext lock];
[managedObjectContext reset];//to drop pending changes
if ([persistentStoreCoordinator removePersistentStore:persistentStore error:&error])
{
NSURL* storeURL = [NSURL fileURLWithPath:[self pathForPersistentStore]];
[[NSFileManager defaultManager] removeFileAtPath:[storeURL path] handler:nil];
[self addPersistentStore];//recreates the persistent store
}
[managedObjectContext unlock];

7 个解决方案

#1


61  

Here's what I have done to clean my Core Data entirely. It works perfectly. This is if you only have one persistent store which is probably the case if you didn't add one more manually. If your managedObjectContext has the same name as here you can simply copy/past it will work.

以下是我完全清理核心数据所做的工作。它完美地运作。如果您只有一个持久性存储,如果您没有手动添加一个,则可能就是这种情况。如果您的managedObjectContext与此处的名称相同,则只需复制/过去即可。

NSError * error;
// retrieve the store URL
NSURL * storeURL = [[managedObjectContext persistentStoreCoordinator] URLForPersistentStore:[[[managedObjectContext persistentStoreCoordinator] persistentStores] lastObject]];
// lock the current context
[managedObjectContext lock];
[managedObjectContext reset];//to drop pending changes
//delete the store from the current managedObjectContext
if ([[managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])
{
    // remove the file containing the data
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
    //recreate the store like in the  appDelegate method
    [[managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];//recreates the persistent store
}
[managedObjectContext unlock];
//that's it !

#2


6  

swift version of @Nicolas Manzini answer:

快速版的@Nicolas Manzini回答:

if let psc = self.managedObjectContext?.persistentStoreCoordinator{

        if let store = psc.persistentStores.last as? NSPersistentStore{

            let storeUrl = psc.URLForPersistentStore(store)

            self.managedObjectContext?.performBlockAndWait(){

                self.managedObjectContext?.reset()

                var error:NSError?
                if psc.removePersistentStore(store, error: &error){
                    NSFileManager.defaultManager().removeItemAtURL(storeUrl, error: &error)
                    psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeUrl, options: nil, error: &error)
                }
            }
        }
    }

#3


5  

Based on @Nicolas Manzini answer I have wrote a Swift 2.1 version with little improvements. I have added an extension to NSManagedObjectContext. Full code below:

根据@Nicolas Manzini的回答,我写了一个Swift 2.1版本,几乎没有什么改进。我添加了NSManagedObjectContext的扩展。完整代码如下:

import Foundation
import CoreData

extension NSManagedObjectContext
{
    func deleteAllData()
    {
        guard let persistentStore = persistentStoreCoordinator?.persistentStores.last else {
            return
        }

        guard let url = persistentStoreCoordinator?.URLForPersistentStore(persistentStore) else {
            return
        }

        performBlockAndWait { () -> Void in
            self.reset()
            do
            {
                try self.persistentStoreCoordinator?.removePersistentStore(persistentStore)
                try NSFileManager.defaultManager().removeItemAtURL(url)
                try self.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
            }
            catch { /*dealing with errors up to the usage*/ }
        }
    }
}

#4


1  

You could loop through all objects and delete them by doing this:

您可以遍历所有对象并通过执行以下操作将其删除:

[managedObjectContext deleteObject:someObject];

If you want to remove all objects it is probably fastest to delete the store and then recreate the CoreData stack.

如果要删除所有对象,可能最快删除存储,然后重新创建CoreData堆栈。

#5


1  

Trash your data file and remake it.

将您的数据文件存档并重新制作。

#6


1  

There is a function

有一个功能

如何从Core Data中的持久存储中删除所有对象?

According to WWDC 242, you can use it for clearing a database.

根据WWDC 242,您可以使用它来清除数据库。

Also there is a func replacePersistentStore which is replacing the current database with a selected one.

还有一个func replacePersistentStore,用当前数据库替换当前数据库。

#7


-3  

The fastest way to ditch everything is to send your managed object context the reset message.

抛弃一切的最快方法是向托管对象上下文发送重置消息。

#1


61  

Here's what I have done to clean my Core Data entirely. It works perfectly. This is if you only have one persistent store which is probably the case if you didn't add one more manually. If your managedObjectContext has the same name as here you can simply copy/past it will work.

以下是我完全清理核心数据所做的工作。它完美地运作。如果您只有一个持久性存储,如果您没有手动添加一个,则可能就是这种情况。如果您的managedObjectContext与此处的名称相同,则只需复制/过去即可。

NSError * error;
// retrieve the store URL
NSURL * storeURL = [[managedObjectContext persistentStoreCoordinator] URLForPersistentStore:[[[managedObjectContext persistentStoreCoordinator] persistentStores] lastObject]];
// lock the current context
[managedObjectContext lock];
[managedObjectContext reset];//to drop pending changes
//delete the store from the current managedObjectContext
if ([[managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])
{
    // remove the file containing the data
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
    //recreate the store like in the  appDelegate method
    [[managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];//recreates the persistent store
}
[managedObjectContext unlock];
//that's it !

#2


6  

swift version of @Nicolas Manzini answer:

快速版的@Nicolas Manzini回答:

if let psc = self.managedObjectContext?.persistentStoreCoordinator{

        if let store = psc.persistentStores.last as? NSPersistentStore{

            let storeUrl = psc.URLForPersistentStore(store)

            self.managedObjectContext?.performBlockAndWait(){

                self.managedObjectContext?.reset()

                var error:NSError?
                if psc.removePersistentStore(store, error: &error){
                    NSFileManager.defaultManager().removeItemAtURL(storeUrl, error: &error)
                    psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeUrl, options: nil, error: &error)
                }
            }
        }
    }

#3


5  

Based on @Nicolas Manzini answer I have wrote a Swift 2.1 version with little improvements. I have added an extension to NSManagedObjectContext. Full code below:

根据@Nicolas Manzini的回答,我写了一个Swift 2.1版本,几乎没有什么改进。我添加了NSManagedObjectContext的扩展。完整代码如下:

import Foundation
import CoreData

extension NSManagedObjectContext
{
    func deleteAllData()
    {
        guard let persistentStore = persistentStoreCoordinator?.persistentStores.last else {
            return
        }

        guard let url = persistentStoreCoordinator?.URLForPersistentStore(persistentStore) else {
            return
        }

        performBlockAndWait { () -> Void in
            self.reset()
            do
            {
                try self.persistentStoreCoordinator?.removePersistentStore(persistentStore)
                try NSFileManager.defaultManager().removeItemAtURL(url)
                try self.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
            }
            catch { /*dealing with errors up to the usage*/ }
        }
    }
}

#4


1  

You could loop through all objects and delete them by doing this:

您可以遍历所有对象并通过执行以下操作将其删除:

[managedObjectContext deleteObject:someObject];

If you want to remove all objects it is probably fastest to delete the store and then recreate the CoreData stack.

如果要删除所有对象,可能最快删除存储,然后重新创建CoreData堆栈。

#5


1  

Trash your data file and remake it.

将您的数据文件存档并重新制作。

#6


1  

There is a function

有一个功能

如何从Core Data中的持久存储中删除所有对象?

According to WWDC 242, you can use it for clearing a database.

根据WWDC 242,您可以使用它来清除数据库。

Also there is a func replacePersistentStore which is replacing the current database with a selected one.

还有一个func replacePersistentStore,用当前数据库替换当前数据库。

#7


-3  

The fastest way to ditch everything is to send your managed object context the reset message.

抛弃一切的最快方法是向托管对象上下文发送重置消息。