當使用NSPrivateQueueConcurrencyType
和NSMainQueueConcurrencyType
類型NSManagedObjectContext
, 是否可以安全地在同一個上下文中執行嵌套的performBlock調用?嵌套performBlock:在NSManagedObjectContext
[backgroundContext performBlock:^{
NSFetchRequest *myRequest = ...;
__block NSArray *result= nil;
[backgroundContext performBlockAndWait:^{
results = [backgroundContext executeFetchRequest:myRequest error:NULL];
}];
}];
這似乎是愚蠢的,但我有很多其封裝executeFetchRequest
來電助手方法現有的代碼庫。我不想對調用者是否已經使用performBlock做出假設。 例如:
-(void)updateObjects:(BOOL)synchronous
{
if (YES == synchronous)
[self fetchHelper];
else
{
[backgroundContext performBlock:^{
[self fetchHelper];
}];
}
}
-(NSArray*)fetchHelper
{
[self.backgroundContext performBlockAndWait:^{
//Fetch the objects...
[self.backgroundContext executeFetchRequest: (...)];
}];
}
我試過了,它的工作原理。但我已經學會了(很難)對Core Data和多線程非常小心。
什麼performBlock,是重入嗎? – malhal
這不是,這是在會議中討論。如果您調用performBlock,您的請求將排隊,因爲它是異步的。 –
只是要清楚,OP在第二位代碼中所做的是可以做到的,但是如果兩種方法都有「performBlock」,會導致問題?這是正確的方式來看待這個? – hokkuk