开发者

Objective-c Http connection - Autorelease no pool - just leaking

开发者 https://www.devze.com 2023-04-10 18:21 出处:网络
I have a http post connection method as shown below: request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];

I have a http post connection method as shown below:

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];
}

It works fine however im getting console messages like __NSAutoreleaseNoPool(): Object 0x62c3b80 of class NSURL autoreleased with no pool in place - just leaking.

开发者_运维百科

using the leaks tool I have narrowed it down to 2 lines which are causing the leaks:

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

and

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

What am I doing wrong?

Thanks in advance


Do not alloc/init/release NSError, it is a reference parameter, just declare it and pass it's address:

NSError *error;

reworked code:

...
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) {
...
0

精彩评论

暂无评论...
验证码 换一张
取 消