Storing and retrieving unsigned long long value to/from NSString

前端 未结 1 435
失恋的感觉
失恋的感觉 2020-12-01 02:27

I have an unsigned long long value which I want to store into an NSString and retrieve from the string.

Initially I have the value in an NSNumber and I am using this

相关标签:
1条回答
  • 2020-12-01 02:59

    There are a lot of ways to accomplish this. The following is the most pragmatic:

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

    This makes a few reasonable assumptions such as numStr will only contain numeric digits and it contains a 'valid' unsigned long long value. A drawback to this approach is that UTF8String creates what essentially amounts to [[numStr dataUsingEncoding:NSUTF8StringEncoding] bytes], or in other words something along the lines of 32 bytes of autoreleased memory per call. For the vast majority of uses, this is no problem what-so-ever.

    For an example of how to add something like unsignedLongLongValue to NSString that is both very fast and uses no autoreleased memory as a side effect, take a look at the end of my (long) answer to this SO question. Specifically the example implementation of rklIntValue, which would require only trivial modifications to implement unsignedLongLongValue.

    More information regarding strtoull can be found in its man page.

    0 讨论(0)
提交回复
热议问题