codescracker


objective c

Objective-C Numbers



« Previous Tutorial Next Tutorial »


You are free to use a wide range of methods in Objective-C to work with NSNumber and some of the important are listed below

(1) This creates and returns an NSNumber object containing a given value, treating it as a signed char

+ (NSNumber *)numberWithChar:(char)value

(2) This creates and returns an NSNumber object containing a given value, and is treating as a BOOL

+ (NSNumber *)numberWithBool:(BOOL)value

(3) This creates and returns an NSNumber object containing a given value, and is treating as a double type

+ (NSNumber *)numberWithDouble:(double)value

(4) This creates and returns an NSNumber object containing a given value, and is treating as signed int type

+ (NSNumber *)numberWithInt:(int)value

(5) This creates and returns an NSNumber object containing a given value, and is treating as a float type

+ (NSNumber *)numberWithFloat:(float)value

(6) This creates and returns an NSNumber object containing a given value, and is treating as NSInteger

+ (NSNumber *)numberWithInteger:(NSInteger)value

(7) This returns the receiver's value as a char type

- (char)charValue

(8) This returns the receiver's value as a BOOL

- (BOOL)boolValue

(9) This returns the receiver's value as a double type

- (double)doubleValue

(10) This returns the receiver's value as an NSInteger

- (NSInteger)integerValue

(11) This returns the receiver's value as a float

- (float)floatValue

(12) This returns the receiver's value as an int type

- (int)intValue

(13) This returns the receiver's value as a human-readable string

- (NSString *)stringValue

Example

Here is an example program for using NSNumber, that simply multiplies the two numbers and returns the product of it:

/* Objective-C Numbers - Example Program */
		
#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
- (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b;
@end

@implementation SampleClass

- (NSNumber *)multiplyA:(NSNumber *)a withB:(NSNumber *)b
{
	float num1 = [a floatValue];
	float num2 = [b floatValue];
	float prod = num1 * num2;
	NSNumber *res = [NSNumber numberWithFloat:prod];
	return res;
}
@end

int main()
{
	NSAutoreleasePool * 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 = %@", resultString);
	[pool drain];
	return 0;
}

When the above code is compile and executed, it will produce the following result:

2014-07-03 13:18:37.932 demo[16787] The product = 105

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test