NSValue

An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object id references. Use this class to work with such data types in collections (such as NSArray and NSSet), key-value coding, and other APIs that require Objective-C objects. NSValue objects are always immutable.

Subclassing Notes

The abstract NSValue class is the public interface of a class cluster consisting mostly of private, concrete classes that create and return a value object appropriate for a given situation. It is possible to subclass NSValue, but doing so requires providing storage facilities for the value (which is not inherited by subclasses) and implementing two primitive methods.

Methods to Override

Any subclass of NSValuemust override the primitive instance methods getValue: and objCType. These methods must operate on the storage that you provide for the value.

You might want to implement an initializer for your subclass that is suited to the storage you provide. The NSValue class does not have a designated initializer, so your initializer need only invoke the init method of super. The NSValue class adopts the NSCopying and NSSecureCoding protocols; if you want instances of your own custom subclass created from copying or coding, override the methods in these protocols.

You may also wish to implement the hash method to make your subclass work well in collections.

Alternatives to Subclassing

If you need only to use NSValue objects for wrap a custom data types or structures defined by your app, you need not create an NSValue subclass. Instead, create a category that uses existing NSValue methods to store and retrieve data of your custom type. For example, the code below defines a custom Polyhedron structure and creates NSValue convenience methods to store and retrieve it:

Return Value

Discussion

This method does not copy the contents of aPointer, so you must not to free the memory at the pointer destination while the NSValue object exists. NSData objects may be more suited for arbitrary pointers than NSValue objects.