Objective-c Http connection - Autorelease no pool - just leaking
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) {
...
精彩评论