简体   繁体   中英

Why is my NSRange always 0?

I want to implement a delete key for my calculator app. My pseudocode for this was:

foo = length of current number
bar = length of current number-1

current number = current number with character at index (foo-bar) removed

To do this in objective-c I have tried to implement this using the NSRange function as well as the StringbyappendingString method:

- (IBAction)DelPressed {
if ([self.display.text length] >=2)
{

    int len = [self.display.text length];//Length of entire display

    //Add to the brainlong printing out the length of the entire display
    self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len];

    int le  = ([self.display.text length]-1);//Length of entire display - 1
    NSString *lestring = [NSString stringWithFormat:@"LE is %g",le];

    //Add to the brainlog printing out the length of the display -1
    self.brainlog.text = [self.brainlog.text stringByAppendingString:lestring];    

    NSRange range = NSMakeRange(le, len);//range only includes the last character

    self.display.text = [self.display.text stringByReplacingCharactersInRange:range withString:@" "];//Replace the last character with whitespace
}

The output to brainlog (ie the length of both le and len) is:

Len is -1.99164 Le is -1.99164

Hard to see, but here's an image of the number I input to the calculator using the iOS simulator: iOS sim图片

I have tried to change the value of le (ie making it the length of the display -3 or -5 etc) and both le and len are still the same.

I have also tried to make le in reference to len:

    int len = [self.display.text length];//Length of entire display
    //Add to the brainlong printing out the length of the entire display
    self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len];


    int le = len-1;

But the values of the two are still the same. How can I use NSRange to delete the last character of the display?

Edit : Using Dustin's fix, I now have reduced a rather lengthy function into 6 lines of code:

    -(IBAction)DelPressed{
    if ([self.display.text length] >=2)
    {
         self.display.text = [self.display.text substringToIndes:[self.display.text length] -1];
    }
 }

Use substring instead; it's much better if all you want to do is remove the last character.

More specifically, substringToIndex(/*length-1*/)

Check this reference out if you need to do other things with strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM