I’ve created a calculator in iOs including each number key as a separate UIButton.
I have an NSString called calcNumberString that holds the number being entered into the calculator. This way I can check to see if the max digit amount has been passed and prevent the user from typing anymore.
In my viewDidLoad event I initialize calcNumberString like so:
calcNumberString = [[NSString alloc] init];
And when I press a number key (5 for example) the following method fires:
-(IBAction)buttonPressed5 : (id) sender
{
if(calcNumberString.length < 10)
{
calcNumberString = [calcNumberString stringByAppendingFormat:@"5"];
calcLabel.text = calcNumberString;
}
}
This works just fine (I can type in up to 10 digits)…. until I hit the CLEAR key:
-(IBAction)buttonPressedClear : (id) sender
{
calcNumberString = @"";
calcLabel.text = @"0"
}
It clears as expected, but when I try to press another number key after that I get EXC_BAD_ACCESS or the following NSInvalidArgumentException:
[__NSCFSet length]: unrecognized selector sent to instance 0x16c110
Is there something in the buttonPressClear method that I’m doing wrong?? It’s obviously the problem as everything works fine until I clear and then try to type in new digits.
Any help would be greatly appreciated.
Thank you!
In your clear button action, you are assigning calcNumberString to another memory location which you have not retain. Once that method goes out of scope, that string memory location is gone.
If you want to continue using NSString, the proper code would be the following:
This way you don’t have any memory leaks.
As @CodaFi mention in the comment, you should be using NSMutableString.