I am a beginner, building a calculator to get myself familiar with ObjC.
So far my code is running ok, except the following code.
This function is linked to 5 buttons.
The problem is when i press any of the buttons the first time, the code runs flawlessly, so does the second time, but falls over the third time. it is always the third time that it fails. On screen on the third press the button itself vanishes and program stalls, and then crashes.
-(void) displayOnScreenValue{
[mainDisplay setText:onScreenTextValue];
}
-(void) pressOperatorButton:(id)sender{
UIButton *pressedOpp = (UIButton *)sender;
onScreenValue = [onScreenTextValue doubleValue]; //onScreenValue is Double
if (!opJustSet) {
switch (opSelected) {
case 0: //Equal
//mainDisplay.text = @"=";
accuValue = onScreenValue;
break;
case 1: //Plus
//mainDisplay.text = @"+";
accuValue = accuValue + onScreenValue;
break;
case 2: //Minus
//mainDisplay.text = @"-";
accuValue = accuValue - onScreenValue;
break;
case 3: //Multiply
//mainDisplay.text = @"x";
accuValue = accuValue * onScreenValue;
break;
case 4: //Divide
//mainDisplay.text = @"d";
accuValue = accuValue / onScreenValue;
break;
default:
break;
}
NSNumber* value = [NSNumber numberWithDouble:accuValue];
onScreenTextValue =[value stringValue];
[self displayOnScreenValue];
opJustSet = YES;
[value release];
}
signChangeSet = NO;
dotUsed = NO;
decimalValue = 0;
opSelected = pressedOpp.tag;
//[self displayOnScreenValue];
[pressedOpp release];
}
In this code:
You should not release value. You only need to release if you called alloc, a copy method,
or if you called retain on it. Most messages return an object that will be autoreleased.
Same goes for this
remove it — you didn’t alloc pressedOpp (or retain it)
Also, I don’t know what onScreenTextValue is, but it should probably be an @property with (retain). If so, you need to access like this:
To get the automatic retaining (in Objective-C self.name and name are not the same thing — the first one uses the property and the second is raw access to the field, which bypasses the generated setter)
Familiarize yourself with reference counting semantics
http://www.loufranco.com/blog/files/managing-memory-iphone.html
-or- Upgrade to latest Xcode and use automatic reference counting.
One other simple thing to do is to always run "Build and Analyze" and make sure to fix every single problem. It’s really good at finding incorrect releases (in fact, this same code is what’s behind automatic reference counting)