djt
djt

Reputation: 7535

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.

Upvotes: 5

Views: 1031

Answers (4)

Avi
Avi

Reputation: 7552

My advice is to use primitive types unless the values will spend a great deal of time in collections (NSArray, NSDictionary, etc.). The @(myInt) syntax is fairly clean, for those times you need an NSNumber.

The one exception I'd keep in mind is when you need to know if the value was ever initialized. In this scenario, unless you have a clear "uninitialized" value (such as zero, NSNotFound, -1, etc.), using NSNumber set to nil makes an easy and deterministic way to tell what you have.

Upvotes: 3

Basically, don't use NSNumber unless you actually, currently need to.

If some API you are using expects NSNumbers, then generate those NSNumber instances on-demand. Basically, use primitives for computations, for storing information, and even in your APIs (e.g. public class properties) as long as it's possible.

Upvotes: 2

StevenUpForever
StevenUpForever

Reputation: 66

In Objective-C, you can do most part of C, so of course, if you needn't to do something about object, you can always use primitive types until you get desired result. Then if you want to insert it in a NSArray or show in UILabel or something, transfer it to NSNumber.

NSInteger is a combination of int/long due to different of 32bit/64bit, other primitive type like float has no problem about this, so only a special OC edition primitive type NSInteger.

NSNumber and primitive type are like Integer vs int in Java I think. You need primitive type to do arithmetic, and NSNumber to do operation about it's object situation and memory space. They can not do the work of the other side.

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299345

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.

Upvotes: 4

Related Questions