Delete/Reset all entries in Core Data?

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

    Here is a somewhat simplified version with less calls to AppDelegate self and the last bit of code that was left out of the top rated answer. Also I was getting an error "Object's persistent store is not reachable from this NSManagedObjectContext's coordinator" so just needed to add that back.

    NSPersistentStoreCoordinator *storeCoordinator = [self persistentStoreCoordinator];
    NSPersistentStore *store = [[storeCoordinator persistentStores] lastObject];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"dataModel"];
    NSError *error;
    
    [storeCoordinator removePersistentStore:store error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
    
    [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
    
    if (storeCoordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:storeCoordinator];
    }
    
    0 讨论(0)
  • 2020-11-22 16:17

    swift solution:

    class func deleteAllManagedObjects() {
    
            let modelURL = NSBundle.mainBundle().URLForResource("some string", withExtension: "mom")
            let mom = NSManagedObjectModel(contentsOfURL: modelURL)
    
            for entityName in mom.entitiesByName.keys {
                let fr = NSFetchRequest(entityName: entityName as String)
                let a = Utility.managedObjectContext().executeFetchRequest(fr, error: nil) as [NSManagedObject]
                for mo in a {
                    Utility.managedObjectContext().deleteObject(mo)
                }
            }
    
            Utility.managedObjectContext().save(nil)
        }
    
    0 讨论(0)
  • 2020-11-22 16:17

    Swift 5.1 Solution

    public static func reset() {
        let coordinator = _persistentContainer.persistentStoreCoordinator
        for store in coordinator.persistentStores where store.url != nil {
            try? coordinator.remove(store)
            try? FileManager.default.removeItem(atPath: store.url!.path)
        }
    }
    
    0 讨论(0)
  • 2020-11-22 16:17

    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];
    }
    
    0 讨论(0)
  • 2020-11-22 16:19

    Works with all versions. Pass entity name and iterate through to delete all the entries and save the context.

    func deleteData(entityToFetch: String, completion: @escaping(_ returned: Bool) ->()) {
        var context = NSManagedObjectContext()
        if #available(iOS 10.0, *) {
            context = self.persistentContainer.viewContext
        } else {
            context = self.managedObjectContext
        }
    
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
        fetchRequest.entity = NSEntityDescription.entity(forEntityName: entityToFetch, in: context)
        fetchRequest.includesPropertyValues = false
        do {
            let results = try context.fetch(fetchRequest) as! [NSManagedObject]
            for result in results {
                context.delete(result)
            }
            try context.save()
            completion(true)
        } catch {
            completion(false)
            print("fetch error -\(error.localizedDescription)")
        }
    }
    
    0 讨论(0)
  • 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).

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