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

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

问题描述

我在我的应用中使用了 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?

谢谢

我找到了这个解决方案:

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

推荐答案

这是我为彻底清理核心数据所做的工作.它完美地工作.这是如果您只有一个持久存储,如果您没有手动添加一个持久存储可能就是这种情况.如果您的 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天全站免登陆