Delete all records in NSManagedObjectContext

前端 未结 2 1352
耶瑟儿~
耶瑟儿~ 2021-02-04 06:53

Is there a way to delete all the records from an NSManagedObjectContext?

I\'m using the following code to insert data:

NSManagedObjectContex         


        
相关标签:
2条回答
  • 2021-02-04 07:11

    To delete all instances of a given entity (we'll use your ShoppingBasket), you can simply fetch all baskets then delete them. It's just a few lines of code:

    NSManagedObjectContext * context = [self managedObjectContext];
    NSFetchRequest * fetch = [[[NSFetchRequest alloc] init] autorelease];
    [fetch setEntity:[NSEntityDescription entityForName:@"ShoppingBasket" inManagedObjectContext:context]];
    NSArray * result = [context executeFetchRequest:fetch error:nil];
    for (id basket in result)
        [context deleteObject:basket];
    

    The alternative in a non-document-based app is to shut down your connection to the data store, delete the actual file, then reconnect (the template code that comes with a standard Core Data project will automatically create the file if it's absent). You then have a brand new, empty store.

    Note, the code example ignores any possible error. Don't do that. :-)

    0 讨论(0)
  • 2021-02-04 07:24

    A much quicker way would be to just remove store entirely. This way you're not wasting any time fetching objects, or enumerating through them as the other answer does.

    NSError *error;
    NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent:@"MyCDStore.sqlite"];
    [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
    

    Don't forget to re-create it after you have deleted it.

    0 讨论(0)
提交回复
热议问题