我遇到了無法解析的Core Data問題。我已經很難了解Core Data中的併發問題,因此我非常小心,只能在performBlock:
和performBlockAndWait:
塊中執行任何核心數據操作。在performBlockAndWait塊內執行提取請求時核心數據發生死鎖
這裏去我的代碼:
/// Executes a fetch request with given parameters in context's block.
+ (NSArray *)executeFetchRequestWithEntityName:(NSString *)entityName
predicate:(NSPredicate *)predicate
fetchLimit:(NSUInteger)fetchLimit
sortDescriptor:(NSSortDescriptor *)sortDescriptor
inContext:(NSManagedObjectContext *)context{
NSCAssert(entityName.length > 0,
@"entityName parameter in executeFetchRequestWithEntityName:predicate:fetchLimit:sortDescriptor:inContext:\
is invalid");
__block NSArray * results = nil;
NSPredicate * newPredicate = [CWFCoreDataUtilities currentUserPredicateInContext:context];
if (predicate){
newPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[newPredicate, predicate]];
}
[context performBlockAndWait:^{
NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:entityName];
request.fetchLimit = fetchLimit;
request.predicate = newPredicate;
if (sortDescriptor) {
request.sortDescriptors = @[sortDescriptor];
}
NSError * error = nil;
results = [context executeFetchRequest:request error:&error];
if (error){
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"Fetch requests are required to succeed."
userInfo:@{@"error":error}];
NSLog(@"ERROR! %@", error);
}
NSCAssert(results != nil, @"Fetch requests must succeed");
}];
return results;
}
當我從兩個不同的線程同時進入該方法,並通過兩個不同的環境中,我導致該行死鎖:results = [context executeFetchRequest:request error:&error];
這是有趣的:似乎兩個線程都無法獲得持久存儲協調器上的一些鎖定,以執行獲取請求。
我所有的上下文都是NSPrivateQueueConcurrencyType
。
我不能把我的手指,爲什麼我鎖定應用程序,我應該做什麼不同。我對Stack Overflow的研究沒有給我什麼,因爲大多數人通過在MOC的隊列上分派獲取請求來修復所有的鎖,我已經這樣做了。
我會很感激這個問題的任何信息。隨意提供文檔鏈接和其他長篇文章:我渴望更多地瞭解各種併發問題和策略。
你能提供代碼:'currentUserPredicateInContext:'和'predicate'建設(他們使用從其他上下文對象中獲取構造)? –
你確定這是一個僵局嗎?我建議你發佈線程的堆棧痕跡 –
@DanShelly該錯誤很難重現,我今天沒有看到它,所以沒有堆棧跟蹤。 謂詞格式爲「owner =%@」,其中%@是來自用戶默認值的字符串。我根本沒有在謂詞中使用任何MObjects。 我相信這是一個死鎖,因爲在堆棧跟蹤中,我的兩個線程停留在mutex_wait上,這是對executeFetchRequest的調用所致。 –