Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 754
Rasto Avatar asked Aug 09 '13 11:08

Rasto


1 Answers

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.

like image 197
Martin R Avatar answered Oct 12 '22 08:10

Martin R