Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Number Objects

All the numeric data types we’ve dealt with up to now, such as integers, floats, and longs, are basic data types in the Objective-C language—that is, they are not objects. For example, you can’t send messages to them. Sometimes, though, you need to work with these values as objects. For example, the Foundation object NSArray enables you to set up an array in which you can store values. These values have to be objects, so you can’t directly store any of your basic data types in these arrays. Instead, to store any of the basic numeric data types (including the char data type), you can use the NSNumber class to create objects from these data types. (See Program 15.1.)

Program 15.1.

// Working with Numbers

#import <Foundation/NSObject.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSValue.h>

#import <Foundation/NSString.h>

int main (int argc, char *argv[])
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSNumber          *myNumber, *floatNumber, *intNumber;
    NSInteger          myInt;

    // integer value

    intNumber = [NSNumber numberWithInteger: 100];
    myInt = [intNumber integerValue];
    NSLog (@"%li", (long) myInt);

    // long value

    myNumber = [NSNumber numberWithLong: 0xabcdef];
    NSLog (@"%lx", [myNumber longValue]);

    // char value

    myNumber = [NSNumber numberWithChar: 'X'];
    NSLog (@"%c", [myNumber charValue]);

    // float value

    floatNumber = [NSNumber numberWithFloat: 100.00];
    NSLog (@"%g", [floatNumber floatValue]);

    // double

    myNumber = [NSNumber numberWithDouble: 12345e+15];
    NSLog (@"%lg", [myNumber doubleValue]);

    // Wrong access here

    NSLog (@"%i", [myNumber integerValue]);

    // Test two Numbers for equality

    if ([intNumber isEqualToNumber: floatNumber] == YES)
        NSLog (@"Numbers are equal");
        NSLog (@"Numbers are not equal");

    // Test if one Number is <, ==, or > second Number

    if ([intNumber compare: myNumber] == NSOrderedAscending)
       NSLog (@"First number is less than second");

    [pool drain];
    return 0;



You are currently reading a PREVIEW of this book.


Get instant access to over $1 million worth of books and videos.


Start a Free 10-Day Trial

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint