繁体   English   中英

为什么我的NSRange总是为0?

[英]Why is my NSRange always 0?

我想为我的计算器应用实现删除键。 我为此的伪代码是:

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
}

脑力输出(即le和len的长度)为:

Len is -1.99164 Le is -1.99164

很难看到,但这是我使用iOS模拟器输入到计算器的数字的图像: iOS sim图片

我试图更改le的值(即使它的显示长度为-3或-5等),而le和len仍然相同。

我还尝试使le引用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];
    }
 }

使用substring代替; 如果您只想删除最后一个字符,那就更好了。

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

如果您需要对字符串进行其他操作,请查阅此参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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