I’m trying to make a plus/minus button on a calculator work, the idea is basically that what the displayed number should be multiplied by -1, unless if it is equal to 0.
I thought I would do it this way;
if greater than 0, prepend a “-” sign,
if less than 0, delete the first character in the string (which is then “-“),
if equal to 0, leave it that way.
That’s how I started with
- (IBAction)plusminusPressed:(id)sender
{
NSString *minusString = [NSString stringWithFormat:@"-"];
NSString *mainLabelString = mainLabel.text;
if (mainLabelString > 0)
mainLabel.text = [minusString stringByAppendingFormat:mainLabelString];
}
And although it does work with numbers greater than 0, it does just add a minus before 0 and numbers less than 0.
How can I get it to work with the other two possibilities, I’ve tried adding
else if ([mainLabelString isEqualToString:@"0"])
mainLabel.text = [mainLabelString];
but then it expects an identifier. What should I do about the other two possibilities, did I even do the first one ok?
Would You do it some other way instead?
The reason you getting the error because you are trying to compare an NSString with numerical 0:
That’s not how it works in Obj-C. You have to compare the value of “mainLabelString” with 0 like
or
or
Checkout the iOS tutorial on iTunes Univ by Standford Univ – Developing Apps for iOS. It has a chapter on building a simple calculator.