1

有人可以解释这段代码吗

- (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 表示它删除了一个字符串?苹果文档中的含义与删除字符有何关系?

4

2 回答 2

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;
   }
}
于 2012-10-11T11:29:17.573 回答
0

|| 是 OR 运算符。至少其中一项陈述必须是真实的。

查看 Apple 的 substringToIndex: 方法的文档

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

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

于 2012-10-11T11:24:38.733 回答