Header Ads

NSNumber - objective C

In Objective C programming language, in order to save the basic data type like int, float, bool in object form.
Objective C provides a range of method to work with NSNumber and important ones are listed in following table.


S.N. Method and Description
1
+(NSNumber)numberWithBool:(BOOL)value
Creates and return an NSNumbr object containing a given value, treating it as a BOOL.
2
+(NSNumber)numberWithChar:(char)value
Creates and return an NSNumbr object containing a given value, treating it as a signed char..
3
+(NSNumber)numberWithDouble:(double)value
Creates and return an NSNumbr object containing a given value, treating it as a double.
4
+(NSNumber)numberWithFloat:(float)value
Creates and return an NSNumbr object containing a given value, treating it as a float.
5
+(NSNumber)numberWithInt:(int)value
Creates and return an NSNumbr object containing a given value, treating it as a signed int.
6
+(NSNumber)numberWithInteger:(NSInteger)value
Creates and return an NSNumbr object containing a given value, treating it as an NSInteger.
7
-(BOOL)boolvalue
Return the receiver's value as a BOOL
8
-(char)charValue
Return the receiver's values as a char.
9
-(double)doubleValue
Return the receiver's values as a double.
10
-(float)floatValue
Return the receiver's values as a float.
11
-(NSNinteger)integerValue
Return the receiver's values as a NSInteger.
12
-(int)intValue
Return the receiver's values as a int.
8
-(NSString *)stringValue
 Return the receiver's values as a human-readable string.



Here is simple example for using NSNumber which multiplies two numbers and return the product.


#import<Foundation/Foundation.h>

@interface SampleClass :NSObject

  - (NSNumber *)multiplyA :(NSNumber *) withB :(NSNumber *)b;

@end

@implementation SampleClass

    - (NSNumber *)multiplyA:(NSNumber *)a withB :(NSNumber *)b
{
       float number1 = [a floatValue];
       float number2 = [b floatValue];
       float product = number1 * number2;
       NSNumber *result = [ NSNumber numberWithFloat : product ];
       return result;
}
@end

int main()
{
    NSAutorelasePool *pool = [[NSAutoreleasePool alloc]init];
    SampleClass *sampleClass = [[SampleClass alloc]init];
    NSNumber *a = [NSNumber numberWithFloat:10.5];
    NSNumber *b = [NSNumber numberWithFloat:10.0];
    NSNumber *result = [sampleClass multiplyA:a withB:b];
    NSString *resultstring = [result stringValue];
    NSLog(@"The product is : %@", resultString);
   [pool drain];
   retutn 0;
}



No comments:

Powered by Blogger.