My guess you are using your code in the wrong manner.
First, each thread must have its own context. So, inside the block operation you need to create a new context and use it within that block.
NSManagedObjectContext *blockContext = [[NSManagedObjectContext alloc] init];
[blockContext setPersistentStoreCoordinator:[managedObjectContext persistentStoreCoordinator]];
Then, if you need to share objects within contexts, use NSManagedObjectID
and not NSManagedObject
.
Before creating that block save the main context or you will have only temporary ids. Otherwise use - (BOOL)obtainPermanentIDsForObjects:(NSArray *)objects error:(NSError **)error
to obtain permanent ids without saving.
NSArray *objectIDs = [arrayOfManagedObjectsToDelete valueForKey:@"objectID"];
Within the block use - (NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID error:(NSError **)error
to retrieve the object you are interested in through blockContext
.
Your code could look like
NSArray *objectIDs = [arrayOfManagedObjectsToDelete valueForKey:@"objectID"];
// add the operation to the queue with a block
[self.coreDataDeletionQueue addOperationWithBlock:^{
NSManagedObjectContext *blockContext = [[NSManagedObjectContext alloc] init];
[blockContext setPersistentStoreCoordinator:[managedObjectContext persistentStoreCoordinator]];
NSError* error = nil;
for (NSManagedObject *objectID in objectIDs) {
// some error handling here...
NSManagedObject* objectToDelete = [existingObjectWithID:objectID error:&error];
[blockContext deleteObject:objectToDelete];
}
if (![blockContext save:&error]) {
NSLog(@"Couldn't save Core-Data state for the deleted objects result: %@", [error localizedDescription]);
}
}];