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
, NSInteger
, long int
, long long int
, float
, or double
, or as a BOOL
. It also defines a compare:
method to determine the ordering of two NSNumber
objects.
NSInteger nine = 9; |
float ten = 10.0; |
NSNumber *nineFromInteger = [NSNumber numberWithInteger:nine]; |
NSNumber *tenFromFloat = [NSNumber numberWithFloat:ten]; |
NSComparisonResult comparison = [nineFromInteger compare:tenFromFloat]; |
// comparison = NSOrderedAscending |
float aFloat = [nineFromInteger floatValue]; |
// aFloat = 9.0 |
BOOL ok = [tenFromFloat boolValue]; |
// ok = YES |
An NSNumber
object records the numeric type with which it is created, and uses the C rules for numeric conversion when comparing NSNumber
objects of different numeric types and when returning values as C numeric types. See any standard C reference for information on type conversion. (Note, though, that if you ask a number for its objCType
, the returned type does not necessarily match the method the receiver was created with.)
If you ask an NSNumber
object for its value using a type that cannot hold the value, you get back an erroneous resultâÂÂfor example, if you ask for the float
value of a number created with a double
that is greater than FLT_MAX
, or the integer
value of a number created with a float
that is greater than the maximum value of NSInteger
.
NSNumber *bigNumber = [NSNumber numberWithFloat:(FLT_MAX)]; |
NSInteger badInteger = [bigNumber integerValue]; |
NSLog(@"bigNumber: %@; badInteger: %d", bigNumber, badInteger); |
// output: "bigNumber: 3.402823e+38; badInteger: 0" |
© 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-02-08)