如何从Core Data中的持久存储中删除所有对象? [英] How do I delete all objects from my persistent store in Core Data?

查看:91
本文介绍了如何从Core Data中的持久存储中删除所有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的核心数据在我的应用程序工作。因此,我获取一个XML文件,将数据解析成模型对象并将其插入到核心数据中。它们保存在持久存储中,我可以在重新启动应用程序时访问它们。但是,我想要能够永久存储中的数据刷新,所以我需要先从存储中删除现有的对象。是否有直接的方法?

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?

感谢

我发现这个解决方案:

[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];


推荐答案

。它工作完美。这是如果你只有一个持久存储,这可能是如果你没有手动添加一个。如果你的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 !

这篇关于如何从Core Data中的持久存储中删除所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆