C primitive types

The collections covered in this chapter only hold objects. What if you want a collection of floats or ints? You can wrap common C number types using NSNumber.

You can create a literal NSNumber instance using the @ symbol – similar to how you create literal NSString instances. For instance, if you wanted to put the numbers 4 and 5.6 into an array, you would create the instance of NSNumber and then add the NSNumber object to the array:

N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​*​l​i​s​t​ ​=​ ​[​[​N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​
[​l​i​s​t​ ​a​d​d​O​b​j​e​c​t​:​@​4​]​;​
[​l​i​s​t​ ​a​d​d​O​b​j​e​c​t​:​@​5​.​6​]​;​

Note that you cannot do math directly with an NSNumber, only with primitives. You must first extract the primitive value using one of several NSNumber methods, do the math, and then re-wrap the result into an NSNumber. You can find the methods for extracting and rewrapping primitive values in the NSNumber class reference.

What about structs? You can wrap a pointer to a struct in an instance of another wrapper class – NSValue (the superclass of NSNumber). Commonly-used structs such as NSPoint (which contains the x and y values of a coordinate) can be boxed using instances of NSValue:

 ​ ​N​S​P​o​i​n​t​ ​s​o​m​e​P​o​i​n​t​ ​=​ ​N​S​M​a​k​e​P​o​i​n​t​(​1​0​0​,​ ​1​0​0​)​;​
 ​ ​N​S​V​a​l​u​e​ ​*​p​o​i​n​t​V​a​l​u​e​ ​=​ ​[​N​S​V​a​l​u​e​ ​v​a​l​u​e​W​i​t​h​P​o​i​n​t​:​s​o​m​e​P​o​i​n​t​]​;​
 ​ ​[​l​i​s​t​ ​a​d​d​O​b​j​e​c​t​:​p​o​i​n​t​V​a​l​u​e​]​;​

NSValue instances can be used to hold just about any scalar value. Read the NSValue class reference to learn more.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset