核心数据:删除实体的所有实例的最快捷方式

我正在使用核心数据来本地保留来自Web服务调用的结果。 Web服务返回完整的对象模型,比方说,“汽车” - 可能大约有2000个(我不能让Web服务返回小于1或所有汽车的任何东西。

下一次打开我的应用程序时,我想通过再次调用所有Cars的Web Service来刷新Core Data持久拷贝,但为了防止重复,我需要首先清除本地缓存中的所有数据。

有没有更快的方法来清除管理对象上下文中的特定实体的所有实例(例如“CAR”类型的所有实体),还是需要查询它们的调用,然后遍历结果以删除每个实例,然后保存?

理想情况下,我可以说删除所有实体是Blah的地方。


iOS 9及更高版本:

iOS 9添加了一个名为NSBatchDeleteRequest的新类,它允许您轻松删除与谓词匹配的对象,而无需将它们全部加载到内存中。 以下是您如何使用它的方法:

斯威夫特2

let fetchRequest = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

do {
    try myPersistentStoreCoordinator.executeRequest(deleteRequest, withContext: myContext)
} catch let error as NSError {
    // TODO: handle the error
}

Objective-C的

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];

NSError *deleteError = nil;
[myPersistentStoreCoordinator executeRequest:delete withContext:myContext error:&deleteError];

有关批量删除的更多信息,请参见WWDC 2015的“核心数据新增功能”会话(从14:10开始)。

iOS 8和更早版本:

取出他们全部并删除他们全部:

NSFetchRequest *allCars = [[NSFetchRequest alloc] init];
[allCars setEntity:[NSEntityDescription entityForName:@"Car" inManagedObjectContext:myContext]];
[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID

NSError *error = nil;
NSArray *cars = [myContext executeFetchRequest:allCars error:&error];
[allCars release];
//error handling goes here
for (NSManagedObject *car in cars) {
  [myContext deleteObject:car];
}
NSError *saveError = nil;
[myContext save:&saveError];
//more error handling here

更清洁和通用一点:添加此方法:

- (void)deleteAllEntities:(NSString *)nameEntity
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:nameEntity];
    [fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID

    NSError *error;
    NSArray *fetchedObjects = [theContext executeFetchRequest:fetchRequest error:&error];
    for (NSManagedObject *object in fetchedObjects)
    {
        [theContext deleteObject:object];
    }

    error = nil;
    [theContext save:&error];
}

Swift 3中重置实体:

func resetAllRecords(in entity : String) // entity = Your_Entity_Name
    {

        let context = ( UIApplication.shared.delegate as! AppDelegate ).persistentContainer.viewContext
        let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
        do
        {
            try context.execute(deleteRequest)
            try context.save()
        }
        catch
        {
            print ("There was an error")
        }
    }
链接地址: http://www.djcxy.com/p/51785.html

上一篇: Core Data: Quickest way to delete all instances of an entity

下一篇: How does type inference work with overloaded generic methods