Problems when using release on NSMutableURLRequest
I have a question on the topic of memory management. When I create a
NSMutableURLRequest
and I release it, after the method return the applicatio开发者_如何学Gon crash.
If I remove the line with release on NSMutableURLRequest
the application works. But it let memory leak.
What´s wrong?
This is the code:
- (NSString *) callServerWhaitReturn {
NSMutableURLRequest * theRequest = [ NSMutableURLRequest requestWithURL: [NSURL URLWithString: self.internalUrl] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 60.0];
[theRequest setHTTPMethod: @"POST"];
[theRequest setHTTPBody:[[NSString stringWithFormat:@"p1=%@", self.parameters] dataUsingEncoding: NSASCIIStringEncoding]];
NSURLResponse * response;
NSError * error;
NSData * result = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &response error: &error];
NSString * toReturn = [[[NSString alloc] initWithData: result encoding:NSASCIIStringEncoding] autorelease];
NSLog(@"%@", toReturn );
[theRequest release];
if (response) {
[response release];
}
if (result) {
[result release];
}
[toReturn autorelease];
return toReturn;
}
requestWithURL:cachePolicy:timeoutInterval:
returns an autoreleased object. If you haven't retained it, you shouldn't be releasing it.
Here are the memory management rules.
NSMutableURLRequest * theRequest = [ NSMutableURLRequest requestWithURL: [NSURL URLWithString: self.internalUrl] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 60.0];
is an auto-released object. You cannot release
it. You have to allocate the object and take ownership only then you should release
it. If you want to release
it then allocate
the object like this
NSMutableURLRequest * theRequest = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: self.internalUrl] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 60.0];
You can't release theRequest
because you did not allocate it.
So remove the below statement from your code.
[theRequest release];
use the initWithURL
method of NSMutableURLRequest
.
精彩评论