iOS 调试器在文本字段中输入 0.0 时崩溃

iOS Debugger Crashes When Inputting 0.0 In Textfield

本文关键字:输入 崩溃 字段 调试器 文本 iOS      更新时间:2023-10-16

我目前正在Xcode中开发iOS应用程序,我想出了计算有效位数的代码。它是用C++写的,但我做了一些更改来让它工作。每当我输入零值时,它都会崩溃,但其他任何东西都可以正常工作。

我的代码如下:

- (IBAction)sigFigCount:(UITextField *)thetextfield
{
length = 0;
if (thetextfield == _textfield1)
{
    if ([thetextfield.text length] > 0)//If TextField Has More Than 0 digits...
    {
        text1 = std::string([_textfield1.text UTF8String]);
        while (text1.at(0) == '0' || text1.at(0) == '.')//Trim Leading Zeros...
        {
            text1 = text1.substr(1);
        }
        length = text1.length();
        decimal = text1.find('.');
        if (decimal >= 0 && decimal < text1.length())//Dont count decimal as sig fig...
        {
            length -= 1;
        }
        if ([[_textfield1 text] doubleValue] == 0.0)
        {
            NSLog(@"HERE");
            self.display3.text = @"1";
        }
        NSString *siggy = [NSString stringWithFormat:@"%i", length];
        self.display3.text = siggy;
    }
    if ([thetextfield.text length] == 0)
    {
        length = 0;
        NSString *ifzero = [NSString stringWithFormat:@"%i", length];
        self.display3.text = ifzero;
    }
    if ([[thetextfield text] doubleValue] == 0.0)
    {
        newLength = 1;
        NSString *zeroVal = [NSString stringWithFormat:@"%i", newLength];
        self.display3.text = zeroVal;
    }
    NSString *norm = [NSString stringWithFormat:@"%i", length];
    self.display3.text = norm;
}
}

请帮忙,我相信这与数字在内存中的表示方式有关......但是当我把它放在一段时间的声明中时,NSLog 起作用了......任何意见都值得赞赏。

谢谢

while (text1.at(0) == '0' || text1.at(0) == '.')//Trim Leading Zeros...
        {
            text1 = text1.substr(1);
        }

我相信这就是你的问题所在。测试字符串"0.0"仅包含 0 和 .字符。循环 3 次后,text1 是空字符串,但您仍在尝试访问第一个字符。

此行也可能不符合您的预期: if ([[文本字段文本] 双倍值] == 0.0)

任何不是数字的东西都会被转换为 0.0,所以[@"foo" doubleValue] == 0.0也是如此。

这里还有很多其他问题,比如使用UTF8String。如果用户键入的不是低 ascii 字符,就会发生奇怪的事情。

你真的不需要在这里C++。仅使用目标 C 就很容易。

其他一些评论...你可能想要 if/else if/else if 而不是 3 个连续的 else。

最后一个 if 也可以很容易地从以下转换:

   if ([[thetextfield text] doubleValue] == 0.0)
    {
        newLength = 1;
        NSString *zeroVal = [NSString stringWithFormat:@"%i", newLength];
        self.display3.text = zeroVal;
    }

if (...) {
  self.display3.text = @"1";
}