If I have this code
NSString *postData = [@"foo=" stringByAppendingString:fooText.text];
...
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
...
[postData release]; //this causes crash
[request release]; //this causes crash
Now I understand this is the expected behavior according to Apple’s documents. Now if i remove the release code the crash doesn’t happen but I find that the memory leaks anyway for *request. So I rewrite the code
NSString *postData;
//postData = [NSString alloc]; // this line commented out since OP
postData = [@"foo=" stringByAppendingString:fooText.text];
...
NSMutableURLRequest *request;
request = [NSMutableURLRequest alloc];
request = [request initWithURL:url];
...
[postData release]; //this still crashes #
[request release]; //this works fine
I don’t really understand why it would crash at # . Is there any recommended best practice here? I think I must be missing something because I often see the ‘shorthand’ approach (top) having a release (Kochan, Programming in Objective-C for example), but the Apple docs say that it’s wrong.
The general rule of thumb, if you are calling a helper static method (such as
stringByAppendingString), then you shouldn’t release it. That string was added to an autorelease pool before being given to you. If you are callingallocthen aninit...method, then you are responsible for releasing that object.Other things to note in your code:
stringByAppendingString, that is a memory leak.[postData release]and[request release]postDataandrequestin your example, so not sure exactly what you are getting at with the two of them.