【问题标题】:Delete all data in each of entity in core data swift3删除核心数据swift3中每个实体中的所有数据
【发布时间】:2017-05-09 06:51:38
【问题描述】:

在核心数据中,我有以下 10 个实体:

 + User
    - x
    - xx
 + Store
    - a
    - aa
 + Point
    - n
    - nn
 + ....

以及如何在核心数据中删除 User、Store、Point 和 .... 中的所有项目

【问题讨论】:

标签: ios core-data swift3


【解决方案1】:

您可以从context.persistentStoreCoordinator.managedObjectModel.entities 获取上下文中的所有实体类型(在您的情况下为 User、Store、Point 等)接下来,对于每个实体,您可以发出获取请求以获取所有实体,然后删除每一个。这也将更新所有正在监视上下文的 FetchedResultsController。如果您不需要这样做,更快的方法是为每个实体使用NSBatchDeleteRequest。不要忘记在最后保存对上下文的更改。

【讨论】:

    【解决方案2】:

    如果您删除 PersistentStoreCoordinator 或 Managedobjectmodel,则可能会出现 persistentStoreCoordinator 冲突和异常。

    所以我所做的是从 coredata 中删除所有实体和对象,而没有形成新的 PersistentStoreCoordinator。

    - (void)deleteDatabase{
        NSArray *entities = self.managedObjectModel.entities;
        for (NSEntityDescription *entityDescription in entities) {
            [self deleteAllObjectsWithEntityName:entityDescription.name inContext:[APPDELEGATE managedObjectContext]]; // Passing the entity name and 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];
        }
    }
    

    使用[self deleteDatabase]; 调用该方法。

    【讨论】:

      猜你喜欢
      • 2017-02-16
      • 2017-08-12
      • 2012-06-22
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多