Objective-C 繼承 C 的基本類型,並引入對象模型。類型系統分為:基本數據類型 (C 兼容)、對象類型 (類/協議指針)、id 類型 (動態綁定萬能指針)。本文系統梳理各類型定義、格式化輸出、限定詞擴展、實戰代碼示例。
| 類型 | 格式符 | 示例 | 說明 |
|---|---|---|---|
| int | %i / %d | 100 | 設備相關寬度 (通常 32 位) |
| long int | %li | 131071100L | 至少 32 位,後綴 L/l |
| long long int | %lli | 1234567890123LL | 至少 64 位 |
| short int | %hi | 32000 | 通常 16 位 |
| unsigned int | %u | 0xFFU | 無符號,後綴 U/u |
十六進制:0xFFED0D,八進制:%o,十六進制帶前綴:%#x。
| 類型 | 格式符 | 示例 | 說明 |
|---|---|---|---|
| float | %f / %e / %g | 13.5f / 1.7e4 | 單精度,後綴 f/F,科學計數法 e/E |
| double | %f / %e / %g | 8.44e+11 | 雙精度,通常 64 位 |
| long double | %Lf / %Le / %Lg | 1.234e+7L | 擴展精度,後綴 L/l |
char:單字符,單引號 'A',格式符 %c。\n \t \\ \" \' \0 等。signed char / unsigned char:當作小整數用 (範圍 -128~127 / 0~255)。NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// NSAutoreleasePool 是類,* 表示指針類型
// 實際上所有對象變量都是指針
id pool = [[NSAutoreleasePool alloc] init]; // 等價
id anyObject = @"string"; // 可指向任何對象
// id 不能指向基本類型 (int/float/struct)
id 定義為 typedef struct objc_object *id;。NSArray/NSDictionary) 存儲的均為 id。在基本類型前添加限定詞,構建豐富類型譜系:
long, long long, shortsigned, unsignedunsigned long long int (64 位無符號),long double (擴展浮點)。#import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
@autoreleasepool { // 現代 ARC 寫法
int integerVar = 100;
float floatingVar = 331.79f;
double doubleVar = 8.44e+11;
char charVar = 'W';
NSLog(@"integerVar = %i", integerVar);
NSLog(@"floatingVar = %f", floatingVar);
NSLog(@"doubleVar = %e", doubleVar); // 科學計數法
NSLog(@"doubleVar = %g", doubleVar); // 自動選擇 %f/%e
NSLog(@"charVar = %c", charVar);
}
return 0;
}
輸出:
integerVar = 100
floatingVar = 331.790009
doubleVar = 8.440000e+11
doubleVar = 8.44e+11
charVar = W
int32_t, uint64_t, intptr_t (stdint.h) 替代 int/long,消除平台差異。double 精度更高、性能無損。char*,統一 NSString (Unicode 就緒、內存管理、豐富 API)。NSArray *names (Xcode 7+),靜態分析捕獲類型錯誤。id,內部邏輯盡量用具體類型/協議 id。Objective-C 類型系統 = C 基本類型 (性能底座) + 對象指針類型 (OO 抽象) + id 動態類型 (極致靈活)。掌握格式化輸出、限定詞組合、id 與靜態類型的邊界,能寫出既高效又安全的現代 Objective-C 代碼。