位置:首頁 > 高級語言 > Objective-C教學 > Objective-C Numbers/數字

Objective-C Numbers/數字

在Objective-C編程語言,為了保存的基本數據類型,如整型,浮點型,布爾對象的形式,

Objective-C中提供了一係列的NSNumber和重要的工作方法是下表中列出。

S.N. 方法和說明
1 + (NSNumber *)numberWithBool:(BOOL)value
Creates and returns an NSNumber object containing a given value, treating it as a BOOL.
2 + (NSNumber *)numberWithChar:(char)value
Creates and returns an NSNumber object containing a given value, treating it as a signed char.
3 + (NSNumber *)numberWithDouble:(double)value
Creates and returns an NSNumber object containing a given value, treating it as a double.
4 + (NSNumber *)numberWithFloat:(float)value
Creates and returns an NSNumber object containing a given value, treating it as a float.
5 + (NSNumber *)numberWithInt:(int)value
Creates and returns an NSNumber object containing a given value, treating it as a signed int.
6 + (NSNumber *)numberWithInteger:(NSInteger)value
Creates and returns an NSNumber object containing a given value, treating it as an NSInteger.
7 - (BOOL)boolValue
Returns the receiver's value as a BOOL.
8 - (char)charValue
Returns the receiver's value as a char.
9 - (double)doubleValue
Returns the receiver's value as a double.
10 - (float)floatValue
Returns the receiver's value as a float.
11 - (NSInteger)integerValue
Returns the receiver's value as an NSInteger.
12 - (int)intValue
Returns the receiver's value as an int.
13 - (NSString *)stringValue
Returns the receiver's value as a human-readable string.

下麵是一個簡單的例子,使用的NSNumber兩個數字相乘,並返回該產品。

#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 number1 = [a floatValue];
   float number2 = [b floatValue];
   float product = number1 * number2;
   NSNumber *result = [NSNumber numberWithFloat:product];
   return result;
}

@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 is %@",resultString);

   [pool drain];
   return 0;
}

現在,當我們編譯並運行程序,我們會得到以下的結果。

2013-09-14 18:53:40.575 demo[16787] The product is 105