Chapter 14. Using NSValue, NSNumber, and NSData
In This Chapter
Boxing Datatypes for Use in Collections
Working with NSNumber, and NSValue
Using NSData and NSMutableData
As I highlight in Chapter 13, when working with collections, collections are capable of storing only valid Objective-C objects. Collections are incapable of storing scalars, structures, or other arbitrary low-level data. This is an inconvenience, but one that the designers of the Foundation framework anticipated and solved.
In order to store scalars and structures in collections, you need to use a class wrapper for these values. In other words, a class that enables you to store the value inside of an object. The Foundation framework provides three primary classes for this purpose, NSValue, NSNumber
, and NSData
.
The NSValue
class is the simplest of these classes, providing a low-level interface for the arbitrary storage of virtually any C datatype. For example, you can store structures within it, you can store ranges within it, and so on. Once the data is stored within the NSValue
instance, you can then use the instance of NSValue
in a collection object. Because NSValue
is relatively low level, it does not provide some of the conveniences of higher-level abstractions. Its purpose is to be flexible but it is limited in its capabilities because it can only store simple stack-allocated data. NSNumber
is a subclass of NSValue
. It provides a higher level abstraction to the NSValue
data encoding system specifically for the purposes ...
Get Objective-C now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.