存储和检索NSString中的无符号long long值

los*_*sit 23 objective-c nsnumber nsstring

我有一个unsigned long long值,我想存储到NSString并从字符串中检索.

最初我在NSNumber中有值,我使用它来获取字符串

NSString *numStr = [NSString stringWithFormat:@"%llu", [myNum unsignedLongLongValue]];
Run Code Online (Sandbox Code Playgroud)

其中myNum是NSNumber.

要从NSString返回NSNumber,我必须首先获得unsigned long long值.但是NSString类中没有方法可以做到这一点(我们只有一个用于获取long long值,而不是unsigned long long值).

有人可以告诉我如何将值恢复到NSNumber变量中.

谢谢.

joh*_*hne 57

有很多方法可以实现这一目标.以下是最实用的:

NSString *numStr = [NSString stringWithFormat:@"%llu", [myNum unsignedLongLongValue]];

// .. code and time in between when numStr was created
// .. and now needs to be converted back to a long long.
// .. Therefore, numStr used below does not imply the same numStr above.

unsigned long long ullvalue = strtoull([numStr UTF8String], NULL, 0);
Run Code Online (Sandbox Code Playgroud)

这做了一些合理的假设,例如numStr只包含数字,它包含一个'有效'无符号long long值.这种方法的一个缺点是,每次调用UTF8String创建基本上相当于[[numStr dataUsingEncoding:NSUTF8StringEncoding] bytes]或者换句话说就是32字节自动释放存储器的行.对于绝大多数用途来说,这不是什么问题.

有关如何添加类似的例子unsignedLongLongValueNSString,既非常快,不使用自动释放内存的副作用,看看我(长)回答年底这太问题.特别是示例实现rklIntValue,只需要进行微不足道的修改即可实现unsignedLongLongValue.

有关更多信息,请参strtoull见其手册页.

  • 为什么不将strtoull的基本参数设置为10而不是0?文档说从0开始的字符串被认为是八进制值,一旦碰巧遇到像这样的字符串,例如来自人类输入,这可能变得很难找到.所以我的建议是:`unsigned long long ullvalue = strtoull([numStr UTF8String],NULL,10);` (5认同)