May I use NSCoder::encodeInteger:forKey: and decodeIntegerForKey: methods with argument of type NSUInteger?

730 Views Asked by At

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.

1

There are 1 best solutions below

2
On

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.