核心数据:删除实体的所有实例的最快方法 [英] Core Data: Quickest way to delete all instances of an entity

查看:37
本文介绍了核心数据:删除实体的所有实例的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Core Data 在本地保存来自 Web 服务调用的结果.Web 服务返回完整的对象模型,比如汽车"——可能是其中的 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?

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

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<NSFetchRequestResult> = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

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

目标-C

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

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

有关批量删除的更多信息可以在 Core 的新功能来自 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆