gpt4 book ai didi

ios - CoreData删除多个对象

转载 作者:技术小花猫 更新时间:2023-10-29 10:06:18 24 4
gpt4 key购买 nike

我知道如何删除 CoreData 中的单个对象我只是想知道是否有更简单的方法来删除多个对象?

对于单个删除你可以使用

[moc deleteObject:someManagedObject];

但是对于多个对象没有等价物。

目前我正在考虑做...

NSArray *arrayOfManagedObjectsToDelete = //...

for (SomeManagedObjectClass *managedObject in arrayOfManagedObjectsToDelete) {
[moc deleteObject:managedObject];
}

但我不确定是否有其他方法可以做到这一点?

理想情况下是像...这样的方法

- (void)deleteObjects:(NSSet*)objects

NSManagedObjectContext 或一些类似的方法上。

最佳答案

iOS 9 及更高版本

swift

let fetchRequest = NSFetchRequest(entityName: "EntityName")
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:@"EntityName"];
NSBatchDeleteRequest *deleteRq = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];

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

iOS 8 及更早版本

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

NSError *error = nil;
NSArray *objects = [myContext executeFetchRequest:fr error:&error];

//error handling goes here
for (NSManagedObject *object in objects) {
[myContext deleteObject:object];
}
NSError *saveError = nil;
[myContext save:&saveError];
//more error handling here

关于ios - CoreData删除多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14560900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com