In Objective-c, there is an int data type. Why do we need to use the numeric object NSNumber? This is because many classes (such as NSArray) require the use of objects, whereas int is not an object.
NSNumber is a numeric object. We can use the NSNumber object to create and initialize different types of numeric objects.
For example:
[Cpp]View plaincopy
- # Import <Foundation/Foundation. h>
-
- NSNumber * myNumber, * floatNumber, * intNumber, * number1;
-
- // Create an integer object
- IntNumber = [NSNumber numberWithInteger: 123];
- NSLog (@ "% I", [intNumber integerValue]);
-
- // Create a long object
- MyNumber = [NSNumber numberWithLong: 0 xababab];
- NSLog (@ "% lx", [myNumber longValue]);
-
- // Create a char object
- MyNumber = [NSNumber numberWithChar: 'K'];
- NSLog (@ "% c", [myNumber charValue]);
-
- // Create a float object
- FloatNumber = [NSNumber numberWithFloat: 123.00];
- NSLog (@ "% f", [floatNumber floatValue]);
-
- // Create a double object
- MyNumber = [NSNumber numberWithDouble: 112233e + 15];
- NSLog (@ "% lg", [myNumber doubleValue]);
-
- // Determine whether the values of the two objects are equal
- If ([intNumber isw.tonumber: floatNumber] = YES ){
- NSLog (@ "equal value ");
- } Else {
- NSLog (@ "The value is not equal ");
- }
-
- // Compare the values of two objects
- If ([intNumber compare: myNumber] = NSOrderedAscending ){
- NSLog (@ "small number on the left ");
- } Else {
- NSLog (@ "the number on the left ");
- }
-
- // Initialize the instance
- Number1 = [[NSNumber alloc] initWithInt: 1000];
- NSLog (@ "% d", [number1 intValueunsigned];
- [Number1 release];
For each basic type, the class method assigns an NSNumber object to it and sets it to the specified value. These methods start with numberWith, followed by the type, such as numberWithLong.
In addition, you can also use the instance method to set the specified value for the NSNumber object previously allocated, all of which start with initWith, such as initWithLong.
For example:
Create and initialize class methods |
Instance initialization method |
Value instance method |
NumberWithChar: |
InitWithChar: |
CharValue |
NumberWithShort: |
InitWithShort: |
ShortValue |
... |
... |
... |
Detailed NSNumber usage in Objective-C