如何转换包含任意原始数据类型(例如intfloatcharunsigned int等)的数字的NSString?问题是,我不知道字符串在运行时将包含哪种数字类型.

我知道怎么做,但我不确定这是否适用于任何类型,以及无符号和浮点值:

long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber]; 
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];

谢谢你的帮助.

推荐答案

使用NSNumberFormatter:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42"];

如果字符串不是有效数字,那么myNumber将是nil.如果它是一个有效的数字,那么你现在有了所有的数据来计算它实际上是什么类型的数字.

Objective-c相关问答推荐

Apple Silicon 上的 dispatch_time 计算失败

我在哪里可以找到 info.plist 文件?

如何打印 NSMutableURLRequest?

在 Objective C 中动态调用类方法

使用正则表达式搜索 NSString

如何向 UILabel 添加滚动功能

将长按手势和拖动手势结合在一起

在 Objective-C 类中混合 C 函数

如何在 UICollectionView 中居中行?

声明变量id和NSObject *有什么区别?

Objective-C 中是否有一些文字字典或数组语法?

从 UIImage 获取 Exif 数据 - UIImagePickerController

Objective C 中的调用方法或发送消息

带有 NSBlockOperation 和队列的 NSURLSession

无法将 searchBar 设置为 firstResponder

每个 ivar 都必须是一个属性吗?

当 UIView 框架更改时,视图内的 AVPlayer 层不会调整大小

状态栏文本 colored颜色 iOS 7

更改 UITextField 占位符字体

Xcode 在调试时判断表达式