A simple container for a single C or Objective-C data item.
- iOS 2.0+
- macOS 10.0+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
NSValue object can hold any of the scalar types such as
char, as well as pointers, structures, and object
id references. Use this class to work with such data types in collections (such as
NSSet), Key-value coding, and other APIs that require Objective-C objects.
NSValue objects are always immutable.
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
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
NSValue class adopts the
NSSecure 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: