Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - when to use NSNumber vs a Primitive

if you know that a certain Integer will need to be used as an object in at least one point in its life cycle, should it be declared and used as NSNumber from the beginning?

I know that calculations should be done using primitive data types and so you say [NSNumber numberWithInteger: myInt]. But if 90% of time you only need a basic data type, does the other 10% justify creating an NSNumber and constantly using [NSNumber intValue] to retrieve your primitive? Are there noticeable performance advantages to sticking with a primitive as long as possible or do the OO advantages of NSNumber outweigh those?

As a newcomer to Objective C, I'm also curious what the best practice is -- coming from languages like Ruby and PHP where this doesn't occur.

like image 293
djt Avatar asked Feb 08 '23 13:02

djt


1 Answers

NSNumber is somewhat rare in Objective-C. Certainly not unheard of, but somewhat rare. If you're in doubt, you want to use NSInteger. I've written whole, large programs without a single NSNumber in them.

The most common use for NSNumber is when you want to put it into an NSArray, NSDictionary or serialize it (for example into NSUserDefaults). Most of the time, numbers are just a property of some other object, as an NSInteger.

like image 132
Rob Napier Avatar answered Feb 20 '23 20:02

Rob Napier