2013-09-21 56 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