rwvaldivia
rwvaldivia

Reputation: 395

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

Upvotes: 0

Views: 1047

Answers (3)

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

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.

Upvotes: 0

paulbailey
paulbailey

Reputation: 5346

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.

Upvotes: 4

visakh7
visakh7

Reputation: 26390

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

Upvotes: 1

Related Questions