我在connectionDidFinishLoading:connection
下载大量数据时在 NSURLConnection 异步委托方法中使用此代码。
- (void)saveCompatibilities:(NSArray *)objects {
//setup tempMoc
UIApplication *app = [UIApplication sharedApplication];
AppDelegate *appDelegate = (AppDelegate *)app.delegate;
NSManagedObjectContext *moc = appDelegate.managedObjectContext;
NSPersistentStoreCoordinator *storeCoordinator = moc.persistentStoreCoordinator;
NSManagedObjectContext *tempMoc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
tempMoc.persistentStoreCoordinator = storeCoordinator;
NSString *entityName = NSStringFromClass([Compatibility class]);
for (NSDictionary *newObjectDict in objects) {
[tempMoc performBlock:^{
Compatibility *object = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:tempMoc];
object.prod1 = newObjectDict[@"prod1"];
object.prod2 = newObjectDict[@"prod2"];
object.prod3 = newObjectDict[@"prod3"];
object.region = newObjectDict[@"region"];
object.result = newObjectDict[@"result"];
NSLog(@"%@", object);
}];
}
//do some other stuff here ...
tempMoc = nil;
}
此代码运行正常并保存了一些对象,但在中间崩溃并出现此错误:
由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“+entityForName:找不到实体名称“兼容性”的 NSManagedObjectModel
我设置了断点并了解到在保存一些tempMoc = nil;
对象后最后一行被击中,但没有离开函数。它只是回到循环中,因为现在是 nil,所以会发生错误。tempMoc
为什么它没有完成对对象数组的循环?它确实离开了循环,为什么不把函数放在一起呢?我假设这是由于多线程,我是新手。