自 Xcode 4.4 (LLVM 4.0) 起,Objective-C 引入字面量語法,讓 NSArray、NSDictionary、NSNumber 的創建像 NSString 一樣簡潔。本文對比新舊寫法,展示現代語法如何減少樣板代碼、提升可讀性、降低出錯率。
// 不可變數組:必須以 nil 結尾
NSArray *oldOne = [NSArray arrayWithObjects:@"1st", @"2nd", @"3th", nil];
// 取值:冗長的消息發送
NSString *s = [oldOne objectAtIndex:1];
// 可變數組:初始化後必須先填滿佔位符,才能 replaceObjectAtIndex
NSMutableArray *oldMutable = [NSMutableArray arrayWithArray:oldOne];
[oldMutable replaceObjectAtIndex:1 withObject:@"disposed"]; // 索引必須已存在
// 不可變數組:@[] 字面量,自動推斷類型、計算長度
NSArray *newOne = @[@"1st", @"2nd", @"3th"];
// 取值:下標語法,像 C 數組一樣直觀
NSString *s = newOne[1];
// 可變數組:直接下標賦值,自動擴容、無需預填
NSMutableArray *newMutable = [NSMutableArray array];
newMutable[2] = @"myObject"; // 直接設置索引 2,中間自動補 nil
核心優勢:消除 nil 結尾易漏、objectAtIndex: 冗長、可變數組「必須先有才能改」的反直覺限制。
NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[o1, o2, o3]
forKeys:@[k1, k2, k3]];
NSDictionary *dict = @{ k1 : o1, k2 : o2, k3 : o3 };
鍵值對直觀映射,順序清晰,編譯期檢查鍵值數量匹配。
NSNumber *n;
n = [NSNumber numberWithChar:'X'];
n = [NSNumber numberWithInt:12345];
n = [NSNumber numberWithUnsignedLong:12345ul];
n = [NSNumber numberWithLongLong:12345ll];
n = [NSNumber numberWithFloat:123.45f];
n = [NSNumber numberWithDouble:123.45];
n = [NSNumber numberWithBool:YES];
NSNumber *n;
n = @'X'; // char
n = @12345; // int
n = @12345ul; // unsigned long
n = @12345ll; // long long
n = @123.45f; // float
n = @123.45; // double
n = @YES; // bool
神奇之處:@'X' 創建字符數字,@YES 創建布爾數字,編譯器根據後綴 (ul/ll/f) 和字面量形式自動選擇正確構造器。
@[] @{} 創建的是不可變對象:需可變請 [NSMutableArray arrayWithArray:@[...]] 或 [NSMutableDictionary dictionaryWithDictionary:@{...}]。int、struct、NULL (需用 [NSNull null])。po 直接支持新語法:LLDB 表達式求值可直接用 @[...] 構造臨時數組。字面量語法是 Objective-C 向現代語言靠攏的關鍵一步:用聲明式替代命令式,用約定優於配置,用編譯器智能替代手工樣板。擁抱新語法,讓代碼更專注於業務邏輯本身。