在计算器应用程序中退回数字

时间:2012-10-10 23:57:05

标签: objective-c cs193p

有人可以解释这段代码

- (IBAction)backspacePressed {
   self.display.text =[self.display.text substringToIndex:
                  [self.display.text length] - 1]; 

   if ( [self.display.text isEqualToString:@""]
      || [self.display.text isEqualToString:@"-"]) {

      self.display.text = @"0";
      self.userIsInTheMiddleOfEnteringNumber = NO;
   }
}

我没有得到目标c中2行的含义。 ||另外,我没有得到substringToIndex的含义。程序员如何知道在我看到substringFromIndex等文档中的所有不同方法中使用substringToIndex。有这么多。这是说索引中的字符串是否计数,-1表示删除字符串?苹果文档中的含义与删除字符有何关系?

2 个答案:

答案 0 :(得分:1)

提供的评论以及代码说明......

- (IBAction)backspacePressed
{
   // This is setting the contents of self.display (a UITextField I expect) to
   // its former string, less the last character.  It has a bug, in that what
   // happens if the field is empty and length == 0?  I don't think substringToIndex
   // will like being passed -1...
   self.display.text =[self.display.text substringToIndex:
                  [self.display.text length] - 1]; 

   // This tests if the (now modified) text is empty (better is to use the length
   // method) or just contains "-", and if so sets the text to "0", and sets some
   // other instance variable, the meaning of which is unknown without further code.
   if ( [self.display.text isEqualToString:@""]
      || [self.display.text isEqualToString:@"-"]) {

      self.display.text = @"0";
      self.userIsInTheMiddleOfEnteringNumber = NO;
   }
}

答案 1 :(得分:0)

||是OR运算符。至少有一个陈述必须是真实的。

查看Apple的substringToIndex:方法文档

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

这是您可以通过Google搜索轻松找到的内容。