我的项目有一个数据库处理程序,其中一个功能是删除数据库中的几乎所有记录。我在单个后台线程上执行实际删除。有时我的代码工作正常,有时它会因NSInternalInconsistencyException而崩溃。目前它在3次尝试中失败了1次。为什么我会收到NSInternalInconsistencyException?我认为只有当你的核心数据功能多线程化时才会发生这种情况。这是我的代码:
//Database handler init.
- (id)init
{
self = [super init];
if(self) {
self.appDelegate = [UIApplication sharedApplication].delegate;
//getting the managedobjectcontext from appdelegate
self.managedObjectContext = self.appDelegate.managedObjectContext;
//background queue
self.backgroundQueue = dispatch_queue_create("database.queue", NULL);
status = 0;
}
return self;
}
//delete majority of the database entry
- (void) clearTables
dispatch_async(self.backgroundQueue, ^(void) {
NSError *error;
//update this entity records.
for(Entity1 *object in [self queryEntity:@"Entity1"]) {
object.download_ymdhms = nil;
[self.managedObjectContext save:nil];
}
[self.managedObjectContext save:&error];
NSLog(@"error1: %@", [error localizedDescription]);
//Delete the other entities data.
for(Entity2 *object in [self queryEntity:@"Entity2"]) {
[self.managedObjectContext deleteObject:object];
}
[self.managedObjectContext save:&error];
NSLog(@"error2: %@", [error localizedDescription]);
for(Entity3 *object in [self queryEntity:@"Entity3"]) {
[self.managedObjectContext deleteObject:object];
}
...
for(Entity10 *object in [self queryEntity:@"Entity10"]) {
[self.managedObjectContext deleteObject:object];
}
[self.managedObjectContext save:&error];
NSLog(@"error3: %@", [error localizedDescription]);
//notify deletion complete
[[NSNotificationCenter defaultCenter] postNotificationName:@"database.queue.delete.done" object:nil];
});
}
//get all the objects in an entity.
- (NSArray *) queryEntity: (NSString *)entity {
return [self queryEntity:entity withPredicate:nil withLimit:0 orderBy:nil];
}
...
//general query
- (NSArray *) queryEntity: (NSString *)entity withPredicate: (NSString *)predicate withLimit: (int)limit orderBy: (NSString *)order
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:entity inManagedObjectContext:self.managedObjectContext]];
if(predicate.length > 0) {
[fetchRequest setPredicate:[NSPredicate predicateWithFormat: predicate]];
}
if(limit > 0) {
[fetchRequest setFetchLimit:limit];
}
if(order.length > 0) {
[fetchRequest setSortDescriptors: @[[[NSSortDescriptor alloc] initWithKey:order ascending:YES]]];
}
NSError *error;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
return results;
}
这是我有时会得到的错误:
CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. statement is still active with userInfo (null)
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'statement is still active'
编辑:添加代码注释以使其更具可读性。