Objective-C question about memory releasing...

I’m teaching myself objective-c/c and I am running across a problem with releasing an object I created…

I have a simple app with a button that would lower a count from 100 by 1. Here’s the method:

-(IBAction) lowerHealth {

//get value of label
NSString* labelvalue = [[NSString alloc] initWithFormat:@"%@", healthpoints.text];

//if it doesn't contain a number then health points = 100
if ([labelvalue isEqualToString:@"Health Points:"]) {
	[msgbox setText: @"Health Points = 100"];
	[healthpoints setText: @"100"];
} else { 
	//get hp value
	int hpoints = [labelvalue intValue] - 1;
	//set msgbox message
	[msgbox setText: @"Lowering Health Points"];
	//convert hpoints to string
	NSString* newhpoints = [NSString stringWithFormat:@"%d", hpoints];
	//set healthpoints message
	[healthpoints setText: [NSString stringWithFormat:@"%d", hpoints]];
	
	[newhpoints release];
}

//relaease stuff
[labelvalue release];

}

If I comment out the [newhpoints release]; line then the method works fine. But if I include it then it breaks. I don’t get an error message it just terminates. I am not setting newhpoints anywhere else in the code nor am I releasing it anywhere else. What am I doing wrong?

Hi,

the rule is:

If you are creating an object with instance methods including init, new or copy
you are the owner of the object and responsible to release it.

If you are creating an object with class methods including the name of the class e.g. [NSString string.]
the class is the owner and you don’t need to care about memory release.

Note: stringWithFormat or initWithFormat is only useful if you want to convert integers or floats to string or
if you want to concatenate strings or for mixed formats.

You can easily write
NSString* labelvalue = healthpoints.text;

Actually you could omit the variable labelvalue at all

[code] //if it doesn’t contain a number then health points = 100
if ([healthpoints.text isEqualToString:@“Health Points:”]) {
[msgbox setText: @“Health Points = 100”];
[healthpoints setText: @“100”];
} else {
//get hp value
int hpoints = [healthpoints.text intValue] - 1;
//set msgbox message
[msgbox setText: @“Lowering Health Points”];
//convert hpoints to string
//set healthpoints message
[healthpoints setText: [NSString stringWithFormat:@“%d”, hpoints]];

}[/code]