核心数据:删除实体的所有实例的最快方式 [英] Core Data: Quickest way to delete all instances of an entity
问题描述
我使用Core Data在本地保存来自Web服务调用的结果。 Web服务返回完整的对象模型,比方说Cars - 可能大约有2000个(而且我不能使Web服务返回小于1或所有的车辆。
I'm using Core Data to locally persist results from a Web Services call. The web service returns the full object model for, let's say, "Cars" - could be about 2000 of them (and I can't make the Web Service return anything less than 1 or ALL cars.
下一次我打开我的应用程序,我想刷新核心数据持久拷贝通过调用所有汽车的Web服务,但是为了防止重复,我需要先清除本地缓存中的所有数据。
The next time I open my application, I want to refresh the Core Data persisted copy by calling the Web Service for all Cars again, however to prevent duplicates I would need to purge all data in the local cache first.
有更快的方法来清除托管对象上下文中特定实体的所有实例(例如CAR类型的所有实体),或者我需要查询他们调用,然后迭代结果删除每个,然后保存?
Is there a quicker way to purge ALL instances of a specific entity in the managed object context (e.g. all entities of type "CAR"), or do I need to query them call, then iterate through the results to delete each, then save?
理想情况下,我可以说删除所有的实体是Blah。
Ideally I could just say delete all where entity is Blah.
推荐答案
iOS 9及更高版本:
iOS 9添加了一个新类 NSBatchDeleteRequest
允许你轻松地删除与谓词匹配的对象,而无需将它们全部加载到内存中。
iOS 9 and later:
iOS 9 added a new class called NSBatchDeleteRequest
that allows you to easily delete objects matching a predicate without having to load them all in to memory. Here's how you'd use it:
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
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开始)。
More information about batch deletions can be found in the "What's New in Core Data" session from WWDC 2015 (starting at ~14:10).
全部提取并删除全部:
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
这篇关于核心数据:删除实体的所有实例的最快方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!