質問

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 ?

役に立ちましたか?

解決

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

他のヒント

|| is an OR operator. At least one of the statements has to be true.

Look at Apple's documentation for the substringToIndex: method

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

This is stuff you could find easily with a google search.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top