Delete/Reset all entries in Core Data?

后端 未结 30 3140
天命终不由人
天命终不由人 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:20

    If you want to delete all objects and do not want to delete the backing files, you can use following methods:

    - (void)deleteAllObjectsInContext:(NSManagedObjectContext *)context
                           usingModel:(NSManagedObjectModel *)model
    {
        NSArray *entities = model.entities;
        for (NSEntityDescription *entityDescription in entities) {
            [self deleteAllObjectsWithEntityName:entityDescription.name
                                       inContext:context];
        }
    }
    
    - (void)deleteAllObjectsWithEntityName:(NSString *)entityName
                                 inContext:(NSManagedObjectContext *)context
    {
        NSFetchRequest *fetchRequest =
            [NSFetchRequest fetchRequestWithEntityName:entityName];
        fetchRequest.includesPropertyValues = NO;
        fetchRequest.includesSubentities = NO;
    
        NSError *error;
        NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
    
        for (NSManagedObject *managedObject in items) {
            [context deleteObject:managedObject];
            NSLog(@"Deleted %@", entityName);
        }
    }
    

    Beware that it may be very slow (depends on how many objects are in your object graph).

提交回复
热议问题