PDA

View Full Version : For very basic numeric quantities why not just use primitives?




zippyfly
Sep 9, 2010, 09:42 PM
Hi,

For very basic numeric quantities why not just use primitives?

I've seen code using NSNumber just to hold an integer, such as the quantity of a certain number of items. Why not just use int?

The setter code has to retain and release the NSNumber. I am wondering why bother? What's the benefit? (Future planning notwithstanding, since I can't imagine that variable to hold anything except for an integer).

Thanks.



lee1210
Sep 9, 2010, 09:47 PM
For an ivar/property there isn't normally much of a reason to wrap. If you need to put something into a collection, that's the normal reason for wrapping something in an NSValue or NSNumber.

-Lee

GorillaPaws
Sep 9, 2010, 10:45 PM
Just to expand a bit on Lee's answer. There are many times when the API you're working with requires an object, not just a primitive. As Lee mentioned, this is most commonly seen with collections such as NSArray. If you want to have an NSArray of ints, you need to wrap them up in NSNumbers before you can stick them in the array.

zippyfly
Sep 11, 2010, 06:20 PM
Many thanks both!