无法在计算器中得到负号消失

时间:2012-07-28 05:00:27

标签: objective-c ios5

我正在使用包含以下代码的iOS 5计算器:

- (IBAction)digitPressed:(UIButton *)sender 
{

//Enter digit, avoiding two-decimal-point case.
NSString *digit = sender.currentTitle;
NSRange range = [self.display.text rangeOfString:@"."];
if (range.location==NSNotFound || (![digit isEqualToString:@"."]))
    if (self.userIsEnteringNumber)
    {
        self.display.text = [self.display.text stringByAppendingString:digit];
    }
    else 
    {
        if (![sender.currentTitle isEqualToString:@"."])
        {
            self.display.text = digit;
        }
        else 
        {
            self.display.text = @"0.";
        }
        self.userIsEnteringNumber = YES;
    }
}

- (IBAction)changeSignPressed 
{

//Reverse sign from positive to negative or vice versa.
if (self.numberIsNegative) self.numberIsNegative = NO;
if (!(self.numberIsNegative)) self.numberIsNegative = YES;

//Correct display to reflect change in sign.
if (self.numberIsNegative)
{
    if (![[self.display.text substringToIndex:1] isEqualToString:@"-"])
    {
        self.display.text = [@"-" stringByAppendingString:self.display.text];
    }
}
if (!self.numberIsNegative)
{ 
     /*This isn't working--why not?
    if ([[self.display.text substringToIndex:1] isEqualToString:@"-"])
    {
        NSLog(@"Okay."); //This doesn't log, so obv. the problem is in the previous line.
        self.display.text = [self.display.text substringFromIndex:1];
    }
     */
}
}

无论我如何操作它,我都无法在changeSignPressed中获得已注释掉的代码。关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:1)

可能是这段代码:

//Reverse sign from positive to negative or vice versa.
if (self.numberIsNegative) self.numberIsNegative = NO;
if (!(self.numberIsNegative)) self.numberIsNegative = YES;

没有else因此如果self.numberIsNegative最初为YES,它将变为NO;然后,它会立即在下一行显示为NO,并将其更改回YES

在任何情况下,该代码都比它需要的更复杂;你可以这样说来反转一个标志:

self.numberIsNegative = ! self.numberIsNegative;