Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>I'm able to work the examples, but he doesn't explain exactly why he's using a class in that way (NSNumber instead of int or double for example)...</em></p> <p><em>There are some things that just don't make sense with Obj-C and Cocoa, why can't I put integers into an NSMutableArray?</em></p> <p><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/nsnumber_Class/Reference/Reference.html#//apple_ref/doc/uid/20000178-3041" rel="noreferrer"><code>NSNumber</code></a> is a much more useful type than a primitive type like <code>int</code> or <code>double</code>, as it is often used in conjunction with other objects you'll run into as you program in Cocoa.</p> <p>For example, in order to package a number as a value into a resizable array (like an <code>NSMutableArray</code>) or an associative array (an instance of <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/doc/uid/20000140-9552" rel="noreferrer"><code>NSDictionary</code></a>), you need to turn the number primitive (<code>int</code>, <code>double</code>, etc.) into a <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/Archiving/Archiving.html" rel="noreferrer">serializable</a>, or archivable object — an <code>NSNumber</code>. </p> <p>Primitives can't be serialized, unlike an <code>NSNumber</code>, because primitives aren't in the basic set of "Core Foundation" types (<code>NSNumber</code>, <code>NSArray</code>, <code>NSString</code>, etc.) that Apple has worked hard to make available to you. </p> <p>Also, by using <code>NSNumber</code> you also get a lot of bonus convenience methods for free: you can quickly convert the number into a string, for example, by simply typing <code>[myNumber stringValue]</code>.</p> <p>Or, if you're treating your <code>NSNumber</code> as the price of something ("$1.23"), you can apply an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html#//apple_ref/doc/uid/20000202-9197" rel="noreferrer"><code>NSNumberFormatter</code></a> to make sure that operations on the number give results that have the format that you would expect (e.g. if you add two price values, you would expect to get a currency value in return).</p> <p>That's not to say you can't or shouldn't use <code>int</code> or <code>double</code> variables. But in many cases, you'll find an <code>NSNumber</code> is a better option, in that you can write less code and get a lot of functionality for "free".</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload