简体   繁体   English

iOS 10 NumberFormatter返回NIL但可在iOS9,iOS8,iOS7上运行

[英]iOS 10 NumberFormatter returns NIL but works on iOS9, iOS8, iOS7

We are communication with a server that sends back numbers in the format: "$229,000" . 我们正在与一台服务器通信,该服务器以以下格式发送回数字: "$229,000"

We use NSNumberFormatter to convert this into a number like: 我们使用NSNumberFormatter将其转换为数字,例如:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencyCode:@"US"];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[formatter setCurrencySymbol:@""];

On any iOS version BELOW iOS-10GM, currency symbol has to be empty string or nil otherwise the formatter fails and returns nil. 在低于iOS-10GM的任何iOS版本上,货币符号必须为空字符串或nil,否则格式化程序将失败并返回nil。

However, on iOS-10 the above code will fail unless we add the currency symbol as "$" . 但是,在iOS-10上,除非我们将货币符号添加为"$"否则上述代码将失败。

Is there any other solutions other than checking iOS version (via NSFoundationVersionNumber )? 除了检查iOS版本(通过NSFoundationVersionNumber )以外,还有其他解决方案吗?

Your code can be made to work on all versions of iOS by changing it as follows: 通过更改代码,可以使您的代码在所有版本的iOS上都可以使用:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

There is no need to set the currency code or symbol since the string you are parsing is already appropriate for the locale being set. 无需设置货币代码或符号,因为您要分析的字符串已经适合于所设置的语言环境。

That code will now properly give a valid NSNumber when passing @"$229,000" to numberFromString: . 现在,在将@"$229,000"传递给numberFromString:时,该代码将正确地提供有效的NSNumber

Tested with iOS 10, 9.3, and 8.4. 在iOS 10、9.3和8.4上进行了测试。

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

相关问题 registerForRemoteNotifications在iOS9上有效,在iOS8上失败 - registerForRemoteNotifications works on iOS9, fails on iOS8 应用程序轮换在iOS7中有效,但在iOS8中无效 - App rotation works in iOS7 but not iOS8 UIScrollview在iOS8中工作,而不在iOS7中工作 - UIScrollview works in iOS8, not in iOS7 本地化不适用于ios8,但适用于ios9和ios10 - Localization doesn't work for ios8 but works for ios9 and ios10 iOS7上的iOS宽高比约束中断,适用于iOS8 - iOS aspect ratio constraint breaks on iOS7, works on iOS8 两个视图之间的转换适用于 iOS8 但不适用于 iOS9 - Transition between two views works on iOS8 but not on iOS9 AFNetworking适用于iOS8,但不适用于iOS9 - AFNetworking works for iOS8, but doesn't work for iOS9 AVPlayer 在 iOS7 中不显示视频,在 iOS8 和 iOS9 上工作正常 - AVPlayer not showing video in iOS7, working fine on iOS8 and iOS9 转换iOS9合并的触摸绘图代码以实现iOS8和iOS7兼容性 - Converting iOS9 coalesced touches drawing code for iOS8 and iOS7 compatibility 导航栏中的“后退”按钮显示在ios7 / ios8中,但未显示在ios9中 - The back button in a navigation bar is shown in ios7/ios8 but not in ios9
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM