Delete/Reset all entries in Core Data?

后端 未结 30 3168
天命终不由人
天命终不由人 2020-11-22 16:00

Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.


Edit

30条回答
  •  耶瑟儿~
    2020-11-22 16:37

    You can delete the SQLite file - but I choose to do it by purging the tables individually with a functions:

    - (void) deleteAllObjects: (NSString *) entityDescription  {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:_managedObjectContext];
        [fetchRequest setEntity:entity];
    
        NSError *error;
        NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
        [fetchRequest release];
    
    
        for (NSManagedObject *managedObject in items) {
            [_managedObjectContext deleteObject:managedObject];
            DLog(@"%@ object deleted",entityDescription);
        }
        if (![_managedObjectContext save:&error]) {
            DLog(@"Error deleting %@ - error:%@",entityDescription,error);
        }
    
    }
    

    The reason I chose to do it table by table is that it makes me confirm as I am doing the programming that deleting the contents of the table is sensible and there is not data that I would rather keep.

    Doing it this will is much slower than just deleting the file and I will change to a file delete if I this method takes too long.

提交回复
热议问题