With the data type of int in objective-c, why use a numeric object NSNumber? This is because many classes, such as Nsarray, require the use of objects, while int is not an object.
NSNumber are numeric objects, and we can use NSNumber objects to create and initialize different types of numeric objects.
#import <Foundation/Foundation.h>
NSNumber *mynumber,*floatnumber,*intnumber,*number1;
Create an integer type Object
intnumber = [NSNumber numberwithinteger:123];
NSLog (@ "%i", [intnumber IntegerValue]);
To create a long type Object
MyNumber = [NSNumber numberwithlong:0xababab];
NSLog (@ "%LX", [MyNumber Longvalue]);
Create a Char type Object
MyNumber = [NSNumber numberwithchar: ' K '];
NSLog (@ "%c", [MyNumber charvalue]);
Create a Float type Object
Floatnumber = [NSNumber numberwithfloat:123.00];
NSLog (@ "%f", [Floatnumber Floatvalue]);
To create a double type object
MyNumber = [NSNumber numberwithdouble:112233e+15];
NSLog (@ "%lg", [MyNumber Doublevalue]);
Determines whether the values of two objects are equal
if ([intnumber isequaltonumber:floatnumber] = = YES) {
NSLog (@ "equal value");
} else {
NSLog (@ "value is not equal");
}
Compare the value size of two objects
if ([intnumber compare:mynumber] = = nsorderedascending) {
NSLog (@ "The number on the left is small");
} else {
NSLog (@ "The number on the left is large");
}
Initializing instances
Number1 = [[NSNumber alloc] initwithint:1000];
NSLog (@ "%d", [Number1 intvalueunsigned];
[Number1 release];
For each base type, the class method assigns a NSNumber object to it and sets it to the specified value, starting with Numberwith, followed by the type, such as Numberwithlong.
In addition, you can use instance methods to set the specified values for previously assigned NSNumber objects, starting with Initwith, such as Initwithlong.
Such as:
creating and Initializing class methods |
Initialize instance methods |
example method of taking value |
Numberwithchar: |
Initwithchar: |
Charvalue |
Numberwithshort: |
Initwithshort: |
Shortvalue |
... |
... |
... |
Objective-c Number Object (NSNumber)