How do I reliably release memory in iPhone app?
iphone, memory
Solution
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 calling `alloc` then an `init...` method, then you are responsible for releasing that object.
Other things to note in your code:
- In the second example, you alloc postData, then immediately replace it with another string created by `stringByAppendingString`, that is a memory leak.
- Your release calls are wrong, they should be `[postData release]` and `[request release]`
- I don't see any correlation between `postData` and `request` in your example, so not sure exactly what you are getting at with the two of them.
Problem
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.