我有以下代碼。任何線索爲什麼我偶爾會陷入僵局?大多數情況下,它工作的很好,看起來當wi-fi到3G轉換髮生或應用程序不活動並返回活動時,發生死鎖。使用GCD和NSData時Web請求鎖定
-(void) dictionaryFromJSONWithURL: (NSURL *) URL callback: (void (^)(NSDictionary* resp, NSError* error)) block{
#ifdef TX_DEBUG
NSLog(@"%s", __FUNCTION__);
#endif
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void){
NSData* data = [NSData dataWithContentsOfURL:URL ];
NSError* error = nil;
NSDictionary* dict = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
dispatch_sync(dispatch_get_main_queue(), ^{
if(error || !dict) block(nil, error);
else block(dict, nil);
});
});
你可以檢查你的代碼,你調用的「回調塊」沒有調用相同的dictionaryFromJSONWithURL:在退出之前?這可能會導致該塊在主隊列(這是串行)中排隊兩次,但第一個等待第二個完成(=死鎖)。 在任何情況下,我同意其他答案:主隊列上的dispatch_sync是麻煩來源。 – viggio24