Delete/Reset all entries in Core Data?

2018-12-31 17:30发布

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

I'm looking to do this programmatically so that a user can essentially hit a reset button.

29条回答
与风俱净
2楼-- · 2018-12-31 17:43

iOS9+, Swift 2

Delete all objects in all entities

func clearCoreDataStore() {
    let entities = managedObjectModel.entities
    for entity in entities {
        let fetchRequest = NSFetchRequest(entityName: entity.name!)
        let deleteReqest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try context.executeRequest(deleteReqest)
        } catch {
            print(error)
        }
    }
}
查看更多
爱死公子算了
3楼-- · 2018-12-31 17:43

Thanks for the post. I followed it and it worked for me. But I had another issue that was not mentioned in any of the replies. So I am not sure if it was just me.

Anyway, thought I would post here the problem and my way that solved it.

I had a few records in the database, I wanted to purge everything clean before write new data to the db, so I did everything including

[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error]; 

and then used managedObjectContext to access the database (supposed to be empty by now), somehow the data was still there. After a while of troubleshooting, I found that I need to reset managedObjectContext, managedObject, managedObjectModel and persistentStoreCoordinator, before I use managedObjectContext to access the dabase. Now I have a clean database to write to.

查看更多
美炸的是我
4楼-- · 2018-12-31 17:45

The accepted answer is correct with removing URL by NSFileManager is correct, but as stated in iOS 5+ edit, the persistent store is not represented only by one file. For SQLite store it's *.sqlite, *.sqlite-shm and *.sqlite-wal ... fortunately since iOS 7+ we can use method

[NSPersistentStoreCoordinator +removeUbiquitousContentAndPersistentStoreAtURL:options:error:]

to take care of removal, so the code should be something like this:

NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSString *storeName = ...;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:storeURL.path options:@{NSPersistentStoreUbiquitousContentNameKey: storeName} error:&error];
查看更多
闭嘴吧你
5楼-- · 2018-12-31 17:46

Use this

+(NSArray *)fetchDataFromEntity:(NSString *)entityName context:(NSManagedObjectContext *)context
{
    NSFetchRequest * fetchRequest =[[NSFetchRequest alloc] init];
    NSEntityDescription * CategoriesEntity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
    [fetchRequest setEntity:CategoriesEntity];

    NSError * error;
    NSInteger count = [context countForFetchRequest:fetchRequest error:&error];

    if (count && count>0) {

        NSArray * fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects && fetchedObjects.count>0) {

            return fetchedObjects;
        }else
            return nil;

    }
    else
        return nil;
}
+ (void)deleteObjectsOfArray:(NSMutableArray*)ary context:(NSManagedObjectContext *)context {
    for (NSManagedObject * obj in ary) {
        [context deleteObject:obj];
    }
    NSError *saveError = nil;
    [context save:&saveError];
}
+ (void)deleteEntity:(NSString *)entityName context:(NSManagedObjectContext *)context {
    NSArray *listArray = [self fetchDataFromEntity:entityName context:context];
    [self deleteObjectsOfArray:[NSMutableArray arrayWithArray:listArray] context:context];
}
查看更多
倾城一夜雪
6楼-- · 2018-12-31 17:47

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).

查看更多
泪湿衣
7楼-- · 2018-12-31 17:47

Delete sqlite from your fileURLPath and then build.

查看更多
登录 后发表回答