Objective-C 作為 C 的超集,引入 Smalltalk 風格的消息機制。本文通過極簡示例演示對象構造、實例/類方法調用,重點解析多參數方法的獨特語法。
@interface / @implementation 分離聲明與實現[[Class alloc] init] 兩步驟(分配 + 初始化)[receiver message] 動態綁定,運行時決議setName:andAge:// Person.h #import@interface Person : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) NSInteger age; // 實例方法 - (void)say:(NSString *)words; - (void)setName:(NSString *)name andAge:(NSInteger)age; - (void)info; // 類方法 + (void)bye; @end // Person.m #import "Person.h" @implementation Person - (void)say:(NSString *)words { NSLog(@"Hi, I am %@", words); } - (void)setName:(NSString *)name andAge:(NSInteger)age { _name = name; _age = age; } - (void)info { NSLog(@"I am info method, name=%@, age=%ld", _name, _age); } + (void)bye { NSLog(@"bye bye !"); } @end
// main.m #import#import "Person.h" int main(int argc, const char *argv[]) { @autoreleasepool { // 1. 構造對象:alloc + init Person *person = [[Person alloc] init]; // 2. 單參數實例方法 [person say:@"I am FansUnion"]; // 3. 多參數實例方法 —— 關鍵語法點 [person setName:@"小雷FansUnion" andAge:26]; // 選擇器完整名稱:setName:andAge: // 參數交織在選擇器片段中,極具可讀性 // 4. 無參實例方法 [person info]; // 5. 無參類方法 [Person bye]; } return 0; }
2015-12-03 20:57:39.023 ObjectPerson[6193:440740] I am test method 2015-12-03 20:57:39.025 ObjectPerson[6193:440740] Hi, I am FansUnion 2015-12-03 20:57:39.025 ObjectPerson[6193:440740] I am info method 2015-12-03 20:57:39.025 ObjectPerson[6193:440740] bye bye ! Program ended with exit code: 0
| 語言 | 調用語法 | 特點 |
|---|---|---|
| C | setNameAndAge(person, "Tom", 20); | 函數調用,參數位置固定 |
| C++ | person.setNameAndAge("Tom", 20); | 成員函數,參數位置固定 |
| Java | person.setNameAndAge("Tom", 20); | 方法調用,參數位置固定 |
| Objective-C | [person setName:@"Tom" andAge:20]; | 消息發送,參數內嵌在選擇器中 |
setName:andAge:"setName:andAge:"(含兩個冒號)NSSelectorFromString(@"setName:andAge:") 動態獲取setName:andAge: 與 setName:andHeight: 完全不同,避免重載衝突[person setName:@"Tom", 20]; —— 逗號分隔是錯誤的[person setNameAndAge:@"Tom" :20]; —— 缺少第二參數標籤[person setName:@"Tom" andAge:20];person.name = @"Tom"; person.age = 20;(編譯器轉為 setter 消息)Objective-C 的消息機制與多參數選擇器語法雖然初學者感到陌生,但體現了「代碼即文檔」的設計哲學。掌握 alloc/init 兩階段構造、實例/類方法區分、選擇器命名規範,是進階學習 Cocoa 框架的基石。