Search code examples
objective-ccs193p

Backspacing a Number in a Calculator App


Can someone explain this code

- (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;
   }
}

I don't get what the 2 lines mean in objective c. || Also, I don't get the meaning of substringToIndex. How does a programmer know to use substringToIndex out of all the different methods in the documentation I saw substringFromIndex etc. There are so many. Is this saying that the strings in the index are counted and -1 means it deletes a string? How would the meaning in the apples documentation relate to deleting a character ?


Solution

  • Comments supplied with explanation of code...

    - (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;
       }
    }