CoreData删除多个对象

时间:2013-01-28 11:20:38

标签: ios objective-c core-data

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

对于单次删除,您可以使用

[moc deleteObject:someManagedObject];

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

目前我正在考虑做...

NSArray *arrayOfManagedObjectsToDelete = //...

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

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

理想情况下是一种方法......

- (void)deleteObjects:(NSSet*)objects

on NSManagedObjectContext或类似方法。

5 个答案:

答案 0 :(得分:22)

iOS 9

<强>夫特

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 
}

<强>目标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

答案 1 :(得分:7)

据我所知,没有一种方法......你应该像你已经做的那样做。有一个名为deletedObjects的方法,但它只返回在下一个保存操作期间将从其持久存储中删除的对象集,如类引用中所述。

答案 2 :(得分:5)

不,没有特定方法可以删除多个对象atm。但我会做这样的事情,与你已经在做的事情相似:

- (void)removeFromManagedObjectContext {
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    fetchRequest.entity = [NSEntityDescription entityForName:@"YourEntity" inManagedObjectContext:managedObjectContext];

    NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:nil];

 
  
    for (Your Entity *Entity in results) {
        [managedObjectContext deleteObject:Entity];
    }
}

答案 3 :(得分:5)

iOS10 &amp; Swift 3

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
    let deleteRequest = NSBatchDeleteRequest( fetchRequest: fetchRequest)

    do{
        try mContext.execute(deleteRequest)
    }catch let error as NSError {//handle error here }

这会删除EntityName的所有对象,但您可以使用NSPredicate

应用其他过滤

答案 4 :(得分:0)

来自https://www.avanderlee.com/swift/nsbatchdeleterequest-core-data/

extension NSManagedObjectContext {
    
    /// Executes the given `NSBatchDeleteRequest` and directly merges the changes to bring the given managed object context up to date.
    ///
    /// - Parameter batchDeleteRequest: The `NSBatchDeleteRequest` to execute.
    /// - Throws: An error if anything went wrong executing the batch deletion.
    public func executeAndMergeChanges(using batchDeleteRequest: NSBatchDeleteRequest) throws {
        batchDeleteRequest.resultType = .resultTypeObjectIDs
        let result = try execute(batchDeleteRequest) as? NSBatchDeleteResult
        let changes: [AnyHashable: Any] = [NSDeletedObjectsKey: result?.result as? [NSManagedObjectID] ?? []]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
    }
}

我的目标是删除一些对象,所以这是我的用法

var objectsToRemove = [NSManagedObjectID]()
// gather objectIDs

let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectsToRemove)
do {
    try defaultContext.executeAndMergeChanges(using: batchDeleteRequest)            
} catch {
    // handle error
}