Note that there are some explanatory texts on larger screens.

plurals
  1. POProper Memory Management for Objective-C Method
    text
    copied!<p>I'm programming an iPhone app and I had a question about memory management in one of my methods. I'm still a little new to managing memory manually, so I'm sorry if this question seems elementary.</p> <p>Below is a method designed to allow a number pad to place buttons in a label based on their tag, this way I don't need to make a method for each button. The method works fine, I'm just wondering if I'm responsible for releasing any of the variables I make in the function.</p> <p>The application crashes if I try to release any of the variables, so I'm a little confused about my responsibility regarding memory.</p> <p>Here's the method:</p> <p>FYI the variable firstValue is my label, it's the only variable not declared in the method.</p> <pre><code>-(IBAction)inputNumbersFromButtons:(id)sender { UIButton *placeHolderButton = [[UIButton alloc] init]; placeHolderButton = sender; NSString *placeHolderString = [[NSString alloc] init]; placeHolderString = [placeHolderString stringByAppendingString:firstValue.text]; NSString *addThisNumber = [[NSString alloc] init]; int i = placeHolderButton.tag; addThisNumber = [NSString stringWithFormat:@"%i", i]; NSString *newLabelText = [[NSString alloc] init]; newLabelText = [placeHolderString stringByAppendingString:addThisNumber]; [firstValue setText:newLabelText]; //[placeHolderButton release]; //[placeHolderString release]; //[addThisNumber release]; //[newLabelText release]; } </code></pre> <p>The application works fine with those last four lines commented out, but it seems to me like I should be releasing these variables here. If I'm wrong about that I'd welcome a quick explanation about when it's necessary to release variables declared in functions and when it's not. Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload