I need to encode and decode property of type NSUInteger
with NSCoder
.
Is it safe to use NSCoder::encodeInteger:forKey:
and NSCoder::decodeIntegerForKey:
methods for that?
The other way around that comes to my mind is to wrap the unsigned integer into NSNumber
first. But that means some more code and I do not like it much.
Is it safe to use NSCoder::encodeInteger:forKey: and NSCoder::decodeIntegerForKey: methods for that?
Yes, it is safe, because all architectures on OS X and iOS use the two's complement for representing signed numbers. For example (assuming a 32-bit architecture), in
NSUInteger n = 0xFFFFFFFF;
[aCoder encodeInteger:n forKey:@"n"];
n
is converted to a signed integer with the same memory representation, which is -1
.
And in
NSUInteger n = [aDecoder decodeIntegerForKey:@"n"];
the signed integer -1
is converted back to an unsigned integer with the same memory representation, so that you get back the original value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With