NSMutableData导致内存泄漏

时间:2011-10-05 10:10:17

标签: iphone objective-c memory-leaks httprequest nsmutabledata

我有一个用于连接httprequests的课程。我收到“NSMutableData”的内存泄漏,但我在“didFailWithError”和连接对象的“connectionDidFinishLoading”中发布它:

- (BOOL)startRequestForURL:(NSURL*)url {

[url retain];


NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
// cache & policy stuff here
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPShouldHandleCookies:YES];
NSURLConnection* connectionResponse = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
if (!connectionResponse)
{
    // handle error
    return NO;
} else {
    receivedData = [[NSMutableData data] retain]; // memory leak here!!!
}

[url release];

[urlRequest release];


return YES;}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
UIAlertView *alert =
[[[UIAlertView alloc]
  initWithTitle:NSLocalizedString(@"Connection problem", nil)
  message:NSLocalizedString(@"A connection problem detected. Please check your internet connection and try again.",nil)

  delegate:self
  cancelButtonTitle:NSLocalizedString(@"OK", nil)
  otherButtonTitles:nil, nil]
 autorelease];
[alert show];

[connectionDelegate performSelector:failedAction withObject:error];
[receivedData release];}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[connectionDelegate performSelector:succeededAction withObject:receivedData];
[receivedData release];}

4 个答案:

答案 0 :(得分:5)

静态分析器会将此称为泄漏,因为您无法保证实际调用任何具有release的方法。

如果您将receivedData设置为保留属性,请执行

self.receivedData = [NSMutableData data];

然后在你的dealloc(以及你的didFail和didFinish,而不是发布):

self.receivedData = nil;

你会好的。

正如jbat100指出的那样,如果是!connectionResponse,你也会泄漏url和urlRequest,除非你从问题中省略了这段代码

答案 1 :(得分:2)

您需要确保这两个委托方法是请求完成的唯一可能方式。我可以在这里看到漏洞

if (!connectionResponse)
{
    // handle error
    return NO;
}

您没有执行发布操作

[url release];
[urlRequest release];

当connectionResponse为非零时,您会执行此操作。另一方面,我强烈建议使用ASIHTTP Obj C库来完成这类工作。

答案 2 :(得分:1)

如果你想要删除这个泄漏,请在.h文件中使用NSURLConnection并在connectionDidFinishLoading方法中释放.reason是你在那里分配了NSURLConnection对象,但如果释放应用程序杀死那里就不能释放那里。这就是为什么你必须在.h

中创建NSURLConnection对象

答案 3 :(得分:0)

为什么你认为你在泄漏? (NSMutableData)如果是因为Xcode的Analyze选项;好吧,它是谎言,因为它甚至无法处理这种明显复杂的情况。

然而,正如Narayana指出的那样,你也在泄漏连接,你应该在完成和失败委托方法中释放它。

相关问题