NSNumberFormatter在设备上返回nil,而不是在模拟器上 [英] NSNumberFormatter returns nil on device, not on simulator

查看:123
本文介绍了NSNumberFormatter在设备上返回nil,而不是在模拟器上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NSNumberFormatter将用户输入转换为NSNumber(十进制数),我使用ARC。

I use a NSNumberFormatter to convert a user input to a NSNumber (a decimal number), I use ARC.

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMaximumFractionDigits:1];

_myNumber = [f numberFromString:myTextField.text];

有时会导致 _myNumber 。即使我绝对确定用户输入的是正确的十进制数(我在调试期间检查过)。

Sometimes this results in _myNumber to be nil. Even when I am absolutely sure the users input is a correct decimal number (I checked during debugging).

为了完整性: _myNumber 是ViewController的综合属性。
只有在设备上运行应用程序时才会发生这种情况,而不是在模拟器中运行时。
使用的键盘是'Decimal Pad'
在不同的代码段中,在不同的ViewController中,代码可以正常工作。

For completeness: _myNumber is a synthesized property of the ViewController. This only happens when running the app on a device, not when I run it in the simulator. The keyboard being used is the ‘Decimal Pad’ In a different section of code, in a different ViewController the code does work.

I现在有一个解决方法,我在上面的代码下面添加了:

I now have a workaround which I have added below the above code:

if (!myNumber){
    myNumber = [NSNumber numberWithFloat: myTextField.text.floatValue];
}

有人知道为什么NSNumberFormatter可以返回nil,即使在调用<$ c $时也是如此c> [NSNumber numberWithFloat:myTextField.text.floatValue] 有效吗?

Does anybody know why NSNumberFormatter can return nil, even when calling [NSNumber numberWithFloat: myTextField.text.floatValue] works?

推荐答案

在我的情况下解决方案是将NSNumberFormatter的decimalSeparator设置为。,例如:

In my case the solution was set the "decimalSeparator" for the NSNumberFormatter to ".", example:

NSNumberFormatter *formatString = [[NSNumberFormatter alloc] init];
formatString.decimalSeparator = @".";

这篇关于NSNumberFormatter在设备上返回nil,而不是在模拟器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆