An object wrapper for primitive scalar numeric values.
SDKs
- iOS 2.0+
- macOS 10.0+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- Foundation
Declaration
class NSNumber : NSValue
Overview
NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char, short int, int, long int, long long int, float, or double or as a BOOL. (Note that number objects do not necessarily preserve the type they are created with.) It also defines a compare(_:) method to determine the ordering of two NSNumber objects.
NSNumber is “toll-free bridged” with its Core Foundation counterparts: CFNumber for integer and floating point values, and CFBoolean for Boolean values. See Toll-Free Bridging for more information on toll-free bridging.
Value Conversions
NSNumber provides readonly properties that return the object’s stored value converted to a particular Boolean, integer, unsigned integer, or floating point C scalar type. Because numeric types have different storage capabilities, attempting to initialize with a value of one type and access the value of another type may produce an erroneous result—for example, initializing with a double value exceeding FLT_MAX and accessing its float, or initializing with an negative integer value and accessing its uint. In some cases, attempting to initialize with a value of a type and access the value of another type may result in loss of precision—for example, initializing with a double value with many significant digits and accessing its float, or initializing with a large integer value and accessing its int8Value.
An NSNumber object initialized with a value of a particular type accessing the converted value of a different kind of type, such as unsigned int and float, will convert its stored value to that converted type in the following ways:
NSNumber from Boolean Value Conversions
| ||||
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
NSNumber from Integer Value Conversions
| ||||
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
| invalid, erroneous result |
|
NSNumber from Unsigned Integer Value Conversions
| ||||
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
NSNumber from Floating Point Value Conversions
| ||||
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
| invalid, erroneous result |
|
Subclassing Notes
As with any class cluster, subclasses of NSNumber must override the primitive methods of its superclass, NSValue. In addition, there are two requirements around the data type your subclass represents:
Your implementation of
objmust return one of “CType c”, “C”, “s”, “S”, “i”, “I”, “l”, “L”, “q”, “Q”, “f”, and “d”. This is required for the other methods ofNSNumberto behave correctly.Your subclass must override the accessor method that corresponds to the declared type—for example, if your implementation of
objreturns “CType i”, you must overrideint32Value.