为什么我总是NSRange 0?(Why is my NSRange always 0?)

2019-10-31 23:22发布

我要实现我的计算器应用程序,删除键。 我对这个伪代码为:

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

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

要做到这一点在Objective-C我已经尝试了本使用NSRange功能还有StringbyappendingString方法来实现:

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

输出到brainlog(即两个文件和len的长度)为:

Len is -1.99164 Le is -1.99164

很难看到,但这里的数字I输入使用的iOS模拟器计算器的图像:

我试图改变的文件(即,使其成为显示-3或-5等的长度)的值和两个文件和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;

但是,这两个值仍然是相同的。 如何使用NSRange删除显示屏的最后一个字符?

编辑 :使用达斯汀的修复,我现在已经减少了一个相当长的功能分为6行的代码:

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

Answer 1:

使用substring代替; 如果你想要做的就是删除最后一个字符是好多了。

更具体地, substringToIndex(/*length-1*/)

检查此引用 ,如果你需要做其他事情处理字符串



文章来源: Why is my NSRange always 0?