且构网

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

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

更新时间:2023-01-06 20:53:54

。它工作完美。这是如果你只有一个持久存储,这可能是如果你没有手动添加一个。如果你的managedObjectContext有与这里相同的名称,你可以简单地复制/过去它将工作。

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.

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 !