首页 文章

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

提问于
浏览
23

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

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

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

其中myNum是NSNumber .

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

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

谢谢 .

1 回答

  • 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);
    

    这使得一些合理的假设,如 numStr 将只包含数字,它包含一个'valid'无符号长long值 . 这种方法的一个缺点是 UTF8String 创建了基本上等于 [[numStr dataUsingEncoding:NSUTF8StringEncoding] bytes] 的内容,或者换句话说,每次调用时沿着32字节自动释放内存的行 . 对于绝大多数用途来说,这不是什么问题 .

    有关如何将 unsignedLongLongValue 添加到 NSString 这样既快速且不使用自动释放内存作为副作用的示例,请查看this SO question的(长)答案的结尾 . 特别是 rklIntValue 的示例实现,它只需要微不足道的修改来实现 unsignedLongLongValue .

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

相关问题