2014-04-09 25 views
0

我需要在GCD塊的NJSONSerialization調用中顯示錯誤。我想創建一個警告,告訴用戶檢查自己的互聯網連接,然後錯誤代碼:錯誤捕獲GCD塊中的NSJSONSerialization

這裏是我的一些代碼:

這是不加緊塊多數民衆贊成在主線程:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) 

然後我有這個

NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: &error]; 

現在我猜錯誤存儲在&錯誤,但我怎麼可以顯示一個警告錯誤我那塊?

一些代碼會很棒。

感謝

回答

1

你會做這樣的事......

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { 
    NSError *error = nil; 

    NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: &error]; 

    if (error) { 
     // you have to show the alert on the main thread 
     dispatch_async(dispatch_get_main_queue, ^(void) { 
      [[[UIAlertView alloc] initWithTitle:@"Error" message:error.userInfo delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; 
     }); 
    } 
}); 

您可能需要基於錯誤的,而不是隻顯示錯誤,以顯示自己的信息。

+2

完美的伴侶,認爲這是summat。將很快投票 – user3480715

+0

酷,很高興它爲你工作:) – Fogmeister

+0

@ user3480715記得接受,如果它回答你的問題。 – Fogmeister