Monday, July 15, 2013

Numbers in Objective C

The basic Datatypes are supported by Objective C including a range of types for working with numbers. This type Datatypes are Known by Primitive datatypes wich means, the value will store in the memory and they are not objects.
To work with number in Object ,we have NSNumber class. NSNumber class is to allow numbers to be stored in an NSArray object and only handles objects.

NSNumber class: to store primitive number in an object form

Creation and initialization methods.
numberWithBool
numberWithChar
numberWithDouble
numberWithFloat
numberWithInt
numberWithInteger
numberWithLong
numberWithLongLong
numberWithShort
numberWithUnsignedChar
numberWithUnsignedInt
numberWithUnsignedInteger
numberWithUnsignedLong
numberWithUnsignedLongLong
numberWithUnsignedShort

Example:-

NSNumber *FloatNo;
FloatNo = [NSNumber numberWithFloat: 3.14];
The above code will be Create a object of NSNumber and assign a float value to it.

It is possible to retrive the number from the object by using instance method. It will be depends on the method used. The list of instance methods are given below.

boolValue
charValue
decimalValue
doubleValue
floatValue
intValue
integerValue
longLongValue
longValue
shortValue
unsignedCharValue
unsignedIntegerValue
unsignedIntValue
unsignedLongLongValue
unsignedLongValue
unsignedShortValue

Example:

NSNumber *FloatNo;
FloatNo = [NSNumber numberWithFloat: 3.14];
Float a=[FloatNo floatValue];
NSLog (@"%f", a);

Comparing Number Objects in Objective C
To compare the value in Number obeject, we have "isEqualToNumber" method or compare methods.

isEqualToNumber

isEqualToNumber method return boolean value.

Example
NSNumber *Float1;
NSNumber *Float2;

Float1 = [NSNumber numberWithDouble: 3.14];
Float2 = [NSNumber numberWithDouble: 3.12];

if ([Float1 isEqualToNumber: Float2])
        NSLog (@"Numbers are equal");
else
        NSLog (@"Numbers are not equal");
Compare Methods

 NSOrderedSame: If the no are equal.
 NSOrderedAscending: check if the first object less than second object.
 NSOrderedDescending: the opposite of  NSOrderedAscending.
 NSComparisonResult :all the comparison methods are return in the form of NSComparisonResult.

Example:

NSNumber *Float1;
NSNumber *Float2;
Float1 = [NSNumber numberWithDouble: 3.14];
Float2 = [NSNumber numberWithDouble: 3.12];
NSComparisonResult Val; 
Val = [Float1 compare: Float2];

if (Val == NSOrderedSame)
        NSLog(@"equal");
else if (Val == NSOrderedAscending)
        NSLog(@"Float1 < Float2");
else if (Val == NSOrderedDescending)
        NSLog(@"Float1 > Float2");
To convert NSNumber to String in Objective C

NSNumber *Float1;
NSString *String1;
Float1 = [NSNumber numberWithDouble: 3.14];
String1 = [Float1 stringValue];
NSLog (@"Number as string is %@", String1);

No comments:

Post a Comment