NSUInteger vs NSInteger, int vs unsigned, and similar cases

You should also be aware of integer conversion rules when dealing with NSUInteger vs. NSInteger:

The following fragment for example returns 0 (false) although you'd expect it to print 1 (true):

NSInteger si = -1;
NSUInteger ui = 1;
printf("%d\n", si < ui);

The reason is that the [si] variable is being implicitly converted to an unsigned int!

See CERT's Secure Coding site for an in-depth discussion around these 'issues' and how to solve them.


By default, an integer is assumed to be signed. In other words the compiler assumes that an integer variable will be called upon to store either a negative or positive number. This limits the extent that the range can reach in either direction. For example, a 32-bit int has a range of 4,294,967,295. In practice, because the value could be positive or negative the range is actually −2,147,483,648 to +2,147,483,647. If we know that a variable will never be called upon to store a negative value, we can declare it as unsigned, thereby extending the (positive) range to 0 to +4,294,967,295. So i would say, its okay to use NSInteger when you know that you have a restricted output range. I personally use NSUInteger if I needed to return really big positive only numbers


If your method has a suitably restricted output range, you might as well use NSInteger since it's easier to type. As you say, if you need to return negative numbers, NSInteger is the only game in town; I'd only use NSUInteger if I needed to return really big numbers for some reason.