views:

24

answers:

1

Hi, another iPhone newbie question...

I have the following:

NSPersistentStoreCoordinator NSManagedObjectContext NSManagedObjectModel

Is it possible to run queries directly on the store (since its a sqlite DB)? I'm trying to delete all the records from a tableview, and figured a "DELETE FROM table" would be nice and quick as opposed to looping through the records and removing them manually (which i'm also struggling with).

Thanks for your time,

James

A: 

Core data acts as a wrapper for the underlying data store, so it's not really a great idea to begin circumventing core data. Additionally, core data adds additional information to your DB, so directly accessing the DB may (or may in the future) cause problems.

To delete all records via core data, I have the following:

+ (void) deleteAll {
  NSManagedObjectContext *managedObjectContext = [(myAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:[[self class] description] inManagedObjectContext:managedObjectContext];
  [fetchRequest setEntity:entity];

  NSError *error;
  NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
  [fetchRequest release];


  for (NSManagedObject *managedObject in items) {
    [managedObjectContext deleteObject:managedObject];
    NSLog(@"%@ object deleted",[[self class] description]);
  }
}
Mr. Matt
Cheers mate. Sorry about the delay.
JT