Thursday, May 19, 2011

NSNumber integerValue example objc

You can extract the integer value from a NSNumber object by calling NSNumber:integerValue method. NSNumber is an general container object for any number(integer, float, double...). Note that NSNumber:integerValue method returns an integer value that is not an object but a native type value. NSInteger is just another name for 'int' type. [NSNumber:integerValue example]

Example>
#import <Foundation/Foundation.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSNumber *objNum;
NSInteger n;
// create a NSNumber object with int value 100.
// it returns an autoreleased object. 
//
objNum = [NSNumber numberWithInt:100];
// Get the integer value from NSNumber.
//
n = [objNum integerValue];
NSLog(@"n:%i",n);
objNum = nil;
 
// allocate a number with Double value. not an autoreleased object.
//
objNum = [[NSNumber alloc]initWithDouble:0.7];
NSLog(@"number:%f", [objNum doubleValue]);
[objNum release];
[pool drain];
return 0; 
}