Objective-c Http连接 - 自动释放没有池 - 只是泄漏

时间:2011-10-04 10:07:02

标签: objective-c http memory memory-leaks autorelease

我有一个http post连接方法,如下所示:

request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:method];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
[request setValue:@"DataType" forHTTPHeaderField:dataType];

[request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
response = nil;
NSError *error = [[NSError alloc] init];

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[request release];
result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseCode = [response statusCode];

[error release];
if(responseCode == 200) {
    [self connectionCompletedHere];
}
else 
{
    [self connectionFailedHere];
}

它工作正常,但我得到像__NSAutoreleaseNoPool()的控制台消息:类NSURL的对象0x62c3b80自动释放没有池到位 - 只是泄漏。

使用泄漏工具我将其缩小到2行,导致泄漏:

[[NSURLConnection alloc] initWithRequest:request delegate:self];

 NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

我做错了什么?

提前致谢

1 个答案:

答案 0 :(得分:0)

不要分配/初始化/释放NSError,它是一个引用参数,只需声明它并传递它的地址:

NSError *error;

重新编写代码:

...
response = nil;
NSError *error;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[request release];
result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseCode = [response statusCode];

if(responseCode == 200) {
...