
- Objective-C 基礎
- Objective-C - 首頁
- Objective-C - 概述
- Objective-C - 環境搭建
- Objective-C - 程式結構
- Objective-C - 基本語法
- Objective-C - 資料型別
- Objective-C - 變數
- Objective-C - 常量
- Objective-C - 運算子
- Objective-C - 迴圈
- Objective-C - 條件判斷
- Objective-C - 函式
- Objective-C - 塊 (Blocks)
- Objective-C - 數字
- Objective-C - 陣列
- Objective-C - 指標
- Objective-C - 字串
- Objective-C - 結構體
- Objective-C - 預處理器
- Objective-C - Typedef
- Objective-C - 型別轉換
- Objective-C - 日誌處理
- Objective-C - 錯誤處理
- 命令列引數
- 高階 Objective-C
- Objective-C - 類與物件
- Objective-C - 繼承
- Objective-C - 多型
- Objective-C - 資料封裝
- Objective-C - 分類 (Categories)
- Objective-C - 模擬 (Posing)
- Objective-C - 擴充套件 (Extensions)
- Objective-C - 協議 (Protocols)
- Objective-C - 動態繫結
- Objective-C - 複合物件
- Obj-C - Foundation 框架
- Objective-C - 快速列舉
- Obj-C - 記憶體管理
- Objective-C 有用資源
- Objective-C - 快速指南
- Objective-C - 有用資源
- Objective-C - 討論
Objective-C 數字
在 Objective-C 程式語言中,為了以物件的形式儲存像 int、float、bool 這樣的基本資料型別,
Objective-C 提供了一系列處理 NSNumber 的方法,重要的方法列在下面的表格中。
序號 | 方法及描述 |
---|---|
1 | + (NSNumber *)numberWithBool:(BOOL)value 建立一個包含給定值的 NSNumber 物件,將其視為 BOOL 型別。 |
2 | + (NSNumber *)numberWithChar:(char)value 建立一個包含給定值的 NSNumber 物件,將其視為有符號 char 型別。 |
3 | + (NSNumber *)numberWithDouble:(double)value 建立一個包含給定值的 NSNumber 物件,將其視為 double 型別。 |
4 | + (NSNumber *)numberWithFloat:(float)value 建立一個包含給定值的 NSNumber 物件,將其視為 float 型別。 |
5 | + (NSNumber *)numberWithInt:(int)value 建立一個包含給定值的 NSNumber 物件,將其視為有符號 int 型別。 |
6 | + (NSNumber *)numberWithInteger:(NSInteger)value 建立一個包含給定值的 NSNumber 物件,將其視為 NSInteger 型別。 |
7 | - (BOOL)boolValue 將接收者的值作為 BOOL 型別返回。 |
8 | - (char)charValue 將接收者的值作為 char 型別返回。 |
9 | - (double)doubleValue 將接收者的值作為 double 型別返回。 |
10 | - (float)floatValue 將接收者的值作為 float 型別返回。 |
11 | - (NSInteger)integerValue 將接收者的值作為 NSInteger 型別返回。 |
12 | - (int)intValue 將接收者的值作為 int 型別返回。 |
13 | - (NSString *)stringValue 將接收者的值作為人類可讀的字串返回。 |
這是一個使用 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