iphone - 为什么我的 NSRange 总是 0?

标签 iphone objective-c ios calculator nsrange

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

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 的输出(即 le 和 len 的长度)是:

Len is -1.99164 Le is -1.99164

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

我已经尝试更改 le 的值(即使它的显示长度为 -3 或 -5 等)并且 le 和 len 仍然相同。

我也试过引用 len 来制作 le:

    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 删除显示的最后一个字符?

编辑:使用 Dustin 的修复程序,我现在将一个相当冗长的函数减少为 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*/)

检查 this reference out 如果你需要用字符串做其他事情

关于iphone - 为什么我的 NSRange 总是 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11567049/

相关文章:

ios - 我正在使用 tableview 从 url 加载图像,但 tableview 中的图像重复问题

ios - 通过 IBInspectable 属性实时渲染 IBOutlet 连接的 subview

ios - 当 2 个选项卡并排共享同一个 tableView 时,UITableView 会产生额外空间

iphone - TestFlight 不报告崩溃

ios - 使用 objective-c/core graphics 的水平居中文本

objective-c - 点击 Storyboard中的按钮时的不同图像

ios - 在 iOS11 上,如何让 UIToolbar 调整所有项目的大小以适应?

ios - iPhone 4 应用程序使用 sqlite 数据库

iphone - 通知用户应用程序商店中应用程序的新更新作为警报并自动在 iPhone 中安装更新版本?

iphone - -(void)textFieldDidBeginEditing :(UITextField *)sender. 。当我选择文本字段时不会调用此函数?