为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

扬帆大鱼 2019-08-14 16:48:28
核心数据:删除实体所有实例的最快方法我正在使用Core Data在本地持久保存Web服务调用的结果。Web服务返回完整的对象模型,比方说,“汽车” - 可能是大约2000个(我不能让Web服务返回任何小于1或所有汽车。下次打开我的应用程序时,我想通过再次调用所有汽车的Web服务来刷新Core Data持久化副本,但是为了防止重复,我需要首先清除本地缓存中的所有数据。是否有更快的方法来清除托管对象上下文中特定实体的所有实例(例如“CAR”类型的所有实体),或者我是否需要查询它们,然后遍历结果以删除每个实例,然后保存?理想情况下,我可以说删除所有实体是Blah的地方。
查看完整描述

3 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

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


查看完整回答
反对 回复 2019-08-14
?
慕丝7291255

TA贡献1859条经验 获得超6个赞

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

- (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];}


查看完整回答
反对 回复 2019-08-14
?
Qyouu

TA贡献1786条经验 获得超11个赞

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")
        }
    }


查看完整回答
反对 回复 2019-08-14
  • 3 回答
  • 0 关注
  • 509 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信