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:
# import
nsnumber * mynumber, * floatnumber, * intnumber, * number1; // create an integer-type object intnumber = [nsnumber numberwithinteger: 123]; nslog (@ "% I ", [intnumber integervalue]); // create a long object mynumber = [nsnumber numberwithlong: 0 xababab]; nslog (@ "% lx", [mynumber longvalue]); // create the char type 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 type 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 (@ "value not equal");} // compare the values of the two objects if ([intnumber compare: mynumber] = nsorderedascending) {nslog (@ "small number on the left");} else {nslog (@ "big 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 |
... |
... |
... |