Delete/Reset all entries in Core Data?

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

    you can also find all the entity names, and delete them by name. Its a longer version but works well, that way you dont have to work with persistence store

     - (void)clearCoreData
    {
    NSError *error;
    NSEntityDescription *des = [NSEntityDescription entityForName:@"Any_Entity_Name" inManagedObjectContext:_managedObjectContext];
    NSManagedObjectModel *model = [des managedObjectModel];
    NSArray *entityNames = [[model entities] valueForKey:@"name"];
    
    for (NSString *entityName in entityNames){
    
        NSFetchRequest *deleteAll = [NSFetchRequest fetchRequestWithEntityName:entityName];
        NSArray *matches = [self.database.managedObjectContext executeFetchRequest:deleteAll error:&error];
    
    }
        if (matches.count > 0){
            for (id obj in matches){
    
                [_managedObjectContext deleteObject:obj];
            }
           [self.database.managedObjectContext save:&error];
        }
    }
    

    for "Any_Entity_Name" just give any one of your entity's name, we only need to figure out the entity description your entities are within. ValueForKey@"name" will return all the entity names. Finally, dont forget to save.

提交回复
热议问题