rwvaldivia rwvaldivia - 1 year ago 85
Objective-C Question

Problems when using release on NSMutableURLRequest

I have a question on the topic of memory management. When I create a

and I release it, after the method return the application crash.

If I remove the line with release on
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;

Answer Source

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.