2013-09-21 54 views
2

我想從MyViewController類做異步URL請求(具有UrlRequestor類):內存泄漏「dispatch_async(dispatch_get_main_queue(),{」塊

UrlRequestor * urlRequestor = [UrlRequestor alloc] init]]; 

我設置MyViewController類爲代表UrlRequestor類:

urlRequestor.delegate = self; 

我打電話getUrlData功能:

[urlRequestor getUrlData]; 

它是UrlRequestor.m文件中的getUrlData函數,用於爲多線程調度隊列。它看起來如此:

- (void) getUrlData { 
    ....... 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
      NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
      ...... 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       ........ 
       [self.delegate receivedGetData: parsedResponseData withActionCode: [NSNumber numberWithInt: DASHBOARD_REQUEST_DONE]]; 
      } 
    } 
} 

我跑的個人資料泄漏的工具,我收到內存在最後一排漏100%:

[self.delegate receivedGetData: parsedResponseData withActionCode: [NSNumber numberWithInt: DASHBOARD_REQUEST_DONE]]; 

我在的iOS是新的,我沒有任何想法,爲什麼我在這裏有內存泄漏。感謝幫助。

+1

我現在試着「分析」。這是一個很好的工具,謝謝。但是這個問題的文件沒有任何警告。 – Tatiana

+0

我們可能應該將其移動到聊天:http://chat.stackoverflow.com/rooms/37800/memory-leak-when-delegate-is-called-from-dispatch-asyncdispatch-get-main-queue – Rob

回答

0

您在塊內使用self。它會導致保留週期。需要使用__weak參考self來打破保留週期。

試試這個,

__weak UrlRequestor *weakSelf = self; 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
     ...... 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      ........ 
      [weakSelf.delegate receivedGetData: parsedResponseData withActionCode: [NSNumber numberWithInt: DASHBOARD_REQUEST_DONE]]; 
      weakSelf = nil; 
     } 

希望幫助!

+0

在「 UrlRequestor.h「文件的」委託「屬性(它是指MyViewController類)被定義爲:」@屬性(弱,非原子)ID 委託;「。我需要重新定義它,或者它可以嗎? – Tatiana

+1

@Tatiana That's correct。代表必須聲明爲「弱」屬性。 – Amar

+5

順便說一句,在調度塊中使用'self'不會導致保留週期。直到代碼塊被分派回主隊列爲止,它只是保留它。在'strong'塊類變量/屬性中使用'self'時,您會得到一個保留週期(aka強參考週期),但在這種情況下不會。話雖如此,在這裏使用'weakSelf'模式並不會造成傷害(儘管最終將其設置爲「nil」是完全沒有必要的),但我認爲它不能解決OP的泄漏問題。 – Rob