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.
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
n
is converted to a signed integer with the same memory representation, which is-1
.And in
the signed integer
-1
is converted back to an unsigned integer with the same memory representation, so that you get back the original value.