What's the difference between NSNumber and NSInteger? Are there more primitives like these that I should know about? Is there one for floats?
The existing answers are useful; adding to them:
Yes, NSUInteger
gives twice the range among positive integers as NSInteger
, but I think another critical reason to choose between the two is simply to distinguish among cases where negative values simply do not make sense.
Example: the return value of NSArray
's count
method is an NSUInteger
, which makes sense since we cannot have an array with a negative number of elements. When the coder knows it's unsigned, he/she has more freedom to perform operations that might be unreliable in the signed case, including bitwise operations such as shifting. This blog post talks more about signed vs unsigned.
My guess about CGFloat
vs NSFloat
(which doesn't exist): It might be the case that the designers of the NeXTStep-named code elements simply didn't need to specify too many float values, outside of time intervals. So they gave NSTimeInterval
, which is a floating-point type, but that is clearly intended for use with time intervals. And, frankly, it's great to have that type because you know it's always meant to be in seconds without having to deal with a struct. When you move into the graphics world (where Core Graphics lives), suddenly floats are all around you, hovering in the air (haha). So it makes sense to introduce a CGFloat
there. This paragraph is all "educated speculation."
Also, just to be clear about why you might use NSInteger
etc instead of primitive types: Because this way it's easier to write portable code that takes full advantage of the machine architecture. For example, a CGFloat
uses 32 bits on some machines and 64 bits on others, depending largely on how much of an efficiency gap there is on those machines for those sizes. In some cases, there's no real speedup for using 32 bits vs 64 bits, so you might as well use 64 bits. If you've declared things as CGFloat
's, you suddenly get that extra precision "for free" when you recompile.
And, as iKenndac has pointed out, NSNumber
is a wrapper class for all of these (and other primitive or quasi-primitive types like the BOOL
) which enables you to include it in your NSArray
s and NSDictionary
s, archive them more easily, and do other things that NSObject
s can do.