Objective-C 是蘋果生態系統的核心語言,採用 **Smalltalk 風格訊息傳遞** (`[obj msg]`) 與 **Foundation 框架**。本文透過兩個 Demo 實作,快速掌握字串比較、不可變/可變陣列操作,並解析語法特異點。
// StringDemo.m #importint main(int argc, const char * argv[]) { @autoreleasepool { NSString *str1 = @"FansUnion"; NSString *str2 = @"XiaoLei"; NSString *str3 = @"XiaoLei"; // 字串長度 NSLog(@"str1 length: %lu", [str1 length]); // 字串比較 (內容比較,非指標比較) if ([str1 isEqualToString:str2]) { NSLog(@"str1 == str2"); } else { NSLog(@"str1 != str2"); } if ([str2 isEqualToString:str3]) { NSLog(@"str2 == str3"); } else { NSLog(@"str2 != str3"); } } return 0; }
str1 length: 9 str1 != str2 str2 == str3
// NumberDemo.m #importint main(int argc, const char * argv[]) { @autoreleasepool { // 不可變陣列 NSArray *names = [NSArray arrayWithObjects: @"FansUnion", @"XiaoLei", nil]; NSLog(@"NSArray!"); for (NSUInteger i = 0; i < [names count]; i++) { NSLog(@"%@", names[i]); // 現代語法等同 [names objectAtIndex:i] } // 可變陣列 NSMutableArray *numbers = [NSMutableArray array]; for (int i = 0; i < 10; i++) { NSNumber *num = [NSNumber numberWithInteger:i]; [numbers addObject:num]; // 訊息傳遞語法 } for (NSUInteger i = 0; i < [numbers count]; i++) { NSLog(@"%@", numbers[i]); } } return 0; }
NSArray! FansUnion XiaoLei 0 1 2 3 4 5 6 7 8 9
| 特性 | C/C++/Java | Objective-C | 說明 |
|---|---|---|---|
| 方法呼叫 | `obj.method()` | `[obj method]` | 訊息傳遞,動態綁定 |
| 帶參方法 | `obj.method(arg)` | `[obj methodWithArg:arg]` | 參數名內建於選擇器 |
| 字串字面量 | `"text"` | `@"text"` | 生成 NSString* 物件 |
| 數值封箱 | `Integer.valueOf(1)` | `@1` 或 `[NSNumber numberWithInt:1]` | 字面量語法糖 |
| 記憶體管理 | 手動/GC | ARC (編譯器自動插入 retain/release) | 編譯期確定生命週期 |
| 介面宣告 | class/interface | @interface / @implementation | 分離介面與實作 |
// C 風格:靜態綁定,編譯期決定調用位址 obj->method(); // OC 風格:動態派發,運行期查找 IMP [obj method]; // 相當於: // id (*msgSend)(id, SEL, ...) = (void*)objc_msgSend; // msgSend(obj, @selector(method));
**優勢**:動態特性支援 Swizzling、KVO、延遲載入等進階模式。**代價**:間接跳轉開銷(現代 CPU 分支預測 + 快取已極小)。
| 操作 | NSArray | NSMutableArray |
|---|---|---|
| 創建 | `[NSArray arrayWithObjects:..., nil]` | `[NSMutableArray array]` |
| 新增 | ❌ | `[arr addObject:obj]` |
| 刪除 | ❌ | `[arr removeObjectAtIndex:i]` |
| 修改 | ❌ | `[arr replaceObjectAtIndex:i withObject:obj]` |
| 查詢 | `[arr objectAtIndex:i]` / `arr[i]` | 同左 |