【发布时间】:2015-10-22 02:02:55
【问题描述】:
我正在使用
-com.apple.CoreData.ConcurrencyDebug
启动时的参数以调试我的 CoreData 应用程序中的并发性。
在应用启动期间,我对主线程的托管对象上下文执行异步获取。
// set up the async request
NSError * error = nil;
[MOC executeRequest:asyncFetch error:&error];
if (error) {
NSLog(@"Unable to execute fetch request.");
NSLog(@"%@, %@", error, error.localizedDescription);
}
这段代码是从主线程调用的,但executeRequest: 将它排入另一个线程,我理解这是正确的行为。
并发调试器不喜欢这样,说(我认为)我在这里做错了什么。我还尝试将其包装在 [MOC performBlock:] 中,这也可以,但也会导致多线程违规。在这两种情况下,我都得到了这个:
[NSManagedObjectContext __Multithreading_Violation_AllThatIsLeftToUsIsHonor__
我是在错误地使用异步获取,还是这里的并发调试器有误?
编辑:我还尝试将它包装在 MOC performBlock 中,这应该确保它从主线程中被调用。在任何情况下,调用都是从主线程入队,但在其他地方执行。
编辑:这是获取请求:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"MyEntity"];
NSPredicate * pred = [NSPredicate predicateWithFormat:@"boolProperty == YES"];
fetchRequest.predicate = pred;
NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
fetchRequest.sortDescriptors = @[sort]; fetchRequest.propertiesToFetch = @[@"prop1", @"prop2", @"prop3", @"prop4"];
NSPersistentStoreAsynchronousFetchResultCompletionBlock resultBlock = ^(NSAsynchronousFetchResult *result) {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:kFetchCompleteNotification object:result];
});
};
NSAsynchronousFetchRequest *asyncFetch = [[NSAsynchronousFetchRequest alloc]
initWithFetchRequest:fetchRequest
completionBlock:resultBlock];
然后我收到通知的结果:
- (void)fetchCompletedNote:(NSNotification *)note {
NSAsynchronousFetchResult * result = note.object;
if (![cachedResults isEqualToArray:result.finalResult]){
cacheResults = result.finalResult;
[self.collectionView reloadData];
}
}
【问题讨论】:
标签: ios multithreading core-data concurrency