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:
NSMutableArray *list = [[NSMutableArray alloc] init]; [list addObject:@4]; [list addObject:@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:
NSPoint somePoint = NSMakePoint(100, 100); NSValue *pointValue = [NSValue valueWithPoint:somePoint]; [list addObject:pointValue];
NSValue instances can be used to hold just about any scalar value. Read the NSValue class reference to learn more.