ios – 为什么NumberFormatter的字符串(来自:)返回一个可选的?

Documentation link

为什么NumberFormatter函数func字符串(来自数字:NSNumber) – >串?返回一个字符串?而不是一个字符串? NumberFormatter是否有特定的输入或状态,此函数可以返回nil?有时我听说这些不太理想的返回类型来自Objective-C保持文件,这是其中一种情况吗?

解决方法

Apple mailing list上有一个古老的(2002)回复,可能部分回答你的问题:

The strange behavior isn’t NSNumber — NSNumber -stringValue seems to be returning results one would expect. It’s NSNumberFormatter which is returning unusual results.

The abstract problem here is that NSNumberFormatter was originally written to handle money amounts for EOF,so it doesn’t deal with unusual numbers well (or general purpose string formatting for that matter).

The more concrete problem is that when you ask an NSNumberFormatter for -stringForObjectValue:,if the object is not an NSDecimalNumber,it converts it to an NSDecimalNumber using
[NSDecimalNumber decimalNumberWithString:[objectValue stringValue]]
which is not going to handle unusual values well,in addition to potentially other issues. A further issue,though I don’t kNow this is the case,is that I don’t think there is an NSDecimal (the struct) representation of positive and negative infinity,as there is for NaN.

我实际上并不理解这种反应足以说明这是为什么返回一个可选项,但我怀疑它是相关的.

原始问题中有示例代码,但没有一个返回nil,它总是给出一个字符串.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...