2

我有一个用于连接 httprequests 的类。尽管我在连接对象的“didFailWithError”和“connectionDidFinishLoading”中释放它,但我得到“NSMutableData”的内存泄漏:

- (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

4 回答 4

5

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

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

self.receivedData = [NSMutableData data];

然后在你的 dealloc 中(还有你的 didFail 和 didFinish,而不是 release):

self.receivedData = nil;

你会没事的。

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

于 2011-10-05T10:22:44.223 回答
2

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

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

你不做发布操作

[url release];
[urlRequest release];

当 connectionResponse 为非 nil 时,你会做什么。另一方面,我强烈建议使用 ASIHTTP Obj C 库来做这类事情。

于 2011-10-05T10:26:30.967 回答
1

如果您想删除此泄漏,请在 .h 文件中获取 NSURLConnection 并在 connectionDidFinishLoading 方法中释放它。原因是您在那里被分配了 NSURLConnection 对象,但如果释放应用程序杀死那里,您不能在那里释放。这就是为什么您必须创建 NSURLConnection 对象在.h

于 2011-10-05T10:20:23.430 回答
0

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

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

于 2011-10-05T10:24:42.757 回答