資料型態種類 | 關鍵字 | 字面常數範例 |
---|---|---|
字元 | char | 'a', '\n' |
整數 | short int | |
整數 | unsigned short int | |
整數 | int | 10, -11, 0xFF3D, 0375 |
整數 | unsigned int | 10u, 100U,0XFFu |
整數 | long int | 10l, -100L, 0xffffL |
整數 | unsigned long int | 10UL, 100ul, 0xfffful |
整數 | long long int | 10LL, 0xffffll |
整數 | unsigned long long int | 10ULL, 0xffffull |
浮點數 | float | 10.1f |
浮點數 | double | 10.1 |
浮點數 | long double | 10.1l |
布林值 | bool | true, false |
任何型態的物件 | id | nil |
不表示型態 | void |
下面程式 (program) 示範利用 sizeof 運算子 (operator) 計算每種基本資料型態所佔的位元組數
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #import <Foundation/Foundation.h> int main ( int argc, const char * argv[]) { NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc ] init ]; NSLog( @"%18s%4d" , " char ", sizeof( char )); NSLog( @"%18s%4d" , " short int ", sizeof( short int )); NSLog( @"%18s%4d" , "unsigned short int ", sizeof(unsigned short int )); NSLog( @"%18s%4d" , " int ", sizeof( int )); NSLog( @"%18s%4d" , "unsigned int ", sizeof(unsigned int )); NSLog( @"%18s%4d" , " long int ", sizeof( long int )); NSLog( @"%18s%4d" , "unsigned long int ", sizeof(unsigned long int )); NSLog( @"%18s%4d" , " long long int ", sizeof( long long int )); NSLog( @"%18s%4d" , " float ", sizeof( float )); NSLog( @"%18s%4d" , " double ", sizeof( double )); NSLog( @"%18s%4d" , " long double ", sizeof( long double )); NSLog( @"%18s%4d" , " id ", sizeof( id )); [pool drain ]; return 0 ; } /* 《程式語言教學誌》的範例程式 檔名:datatype.m 功能:Objective-c 程式範例 作者:張凱慶 時間:西元 2013 年 4 月 */ |
編譯執行,結果如下

32 位元電腦跟 64 位元電腦的結果可能會不同。
使用任何基本資料型態的變數前都需要先宣告,之後利用指派運算子賦予初值,如果沒有給予初值,變數中所儲存的會是記憶體中的殘值。
在 Objective-C 中,凡是物件 (object) 都要用指標 (pointer) 儲存,下例的 pool 與 s 都是指標變數 (variable)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #import <Foundation/Foundation.h> int main ( int argc, const char * argv[]) { NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc ] init ]; NSString *s = @"\n\nThere is no spoon.\n\n" ; NSLog(s); [pool drain ]; return 0 ; } /* 《程式語言教學誌》的範例程式 檔名:pdemo.m 功能:Objective-c 程式範例 作者:張凱慶 時間:西元 2013 年 4 月 */ |
編譯執行,結果如下

沒有賦予初值的指標會造成 Segmentation fault ,應盡量避免。
中英文術語對照 | |
---|---|
基本資料型態 | basic data type |
程式 | program |
運算子 | operator |
物件 | object |
指標 | pointer |
變數 | variable |
您可以繼續參考
基本概念
標記
基本資料型態與指標
相關目錄
Objective-C 快速導覽
Objective-C 教材
首頁
參考資料
Programming with Objective-C: About Objective-C
Programming with Objective-C: Working with Objects
沒有留言:
張貼留言