views:

278

answers:

3

Hi all, 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?

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];
+2  A: 

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.

Felix
A: 

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

Giao
Won't that just empty the context but leave my objects in the persistent store?
Griffo
Save the context afterwards.
Giao
That is wrong. If you have objects in your persistent store these will get refetched with the next fetchRequest. All that reset does is to invalidate all references to managedObjects that the context currently holds.
Felix
+1  A: 

Trash your data file and remake it.

Dave DeLong