Contents

NSValue

A simple container for a single C or Objective-C data item.

Declaration

class NSValue

Overview

An NSValue object 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 NSValue must 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:

typedef struct {
    int numFaces;
    float radius;
} Polyhedron;
 
@interface NSValue (Polyhedron)
+ (instancetype)valuewithPolyhedron:(Polyhedron)value;
@property (readonly) Polyhedron polyhedronValue;
@end
 
@implementation NSValue (Polyhedron)
+ (instancetype)valuewithPolyhedron:(Polyhedron)value
{
    return [self valueWithBytes:&value objCType:@encode(Polyhedron)];
}
- (Polyhedron) polyhedronValue
{
    Polyhedron value;
    [self getValue:&value];
    return value;
}
@end

Topics

Working with Raw Values

Working with Pointer and Object Values

Working with Range Values

Working with Foundation Geometry Values

Working with CoreGraphics Geometry Values

Working with UIKit Geometry Values

Working with CoreAnimation Transform Values

Working with Media Time Values

Working with Geographic Coordinate Values

Working with SceneKit Vector and Matrix Values

Comparing Value Objects

Initializers

Instance Properties

Instance Methods

See Also

Value Wrappers and Transformations