I am trying to make a square button for a calculator, it should take the value from the MainLabel, multiply it with itself and then update it to show the result.
The code I’m using is :
- (IBAction)squarePressed:(id)sender
{
NSString *mainLabelString = mainLabel.text;
int mainlabelValue = [mainLabelString intValue];
NSString *calculatedValue = ((mainlabelValue)*(mainlabelValue));
mainLabel.text = calculatedValue;
}
When I press the button in the simulator, it pauses and thread 1 says this for the last line;
Thread 1: EXC_BAD_ACCESS (code=2, address= 0x51)
What does this mean, what should I do?
It means that you try to access an object where there is none. A message has been sent to an object that has either been deallocated or to a pointer that points to garbage in the memory.
You should set a breakpoint in your method and debug; in order to see if your code is hit. If it is, it is simply a matter of stepping through and identifying the offending line, then figuring out which pointer is bad (try printing the objects with the debugger).
It is impossible for us to know the exact source of your error, but if I should try to guess based on your code, perhaps you forgot to hookup
mainLabelin Interface Builder, and therefore it does not point to a valid label when your method is run ?The next (and more likely) source of your error is that you assign the
mainLabel.textpointer an integer value. You should get a warning here, but if you ignore that, the integer will be assigned as a pointer. Obviously the chances of that integer being a pointer to a valid ObjC object is very slim, so the program fails when it tries to accessmainLabel.textagain. As explained in another answer, you should create a string with the number:Was the number you tried with when you got the error by any chance 9 ? The message says you tried to access memory location 0x51, which coincidentally is 81 = 9*9 in decimal. Using
stringWithFormatto format the number as a string, and assigning the returned string pointer to the string pointer propertymainLabel.textwill resolve your issue. You need to be careful about your types.