Proper Memory Management for Objective-C Method

Posted by Justin on Stack Overflow See other posts from Stack Overflow or by Justin
Published on 2011-01-06T23:22:03Z Indexed on 2011/01/06 23:53 UTC
Read the original article Hit count: 217

Hi, 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.

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.

The application crashes if I try to release any of the variables, so I'm a little confused about my responsibility regarding memory.

Here's the method:

FYI the variable firstValue is my label, it's the only variable not declared in the method.

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

}

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.

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c