首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Objective-C 現代語法糖:NSArray/NSDictionary/NSNumber 字面量寫法演進指南

     編輯:關於C語言

前言:從冗長到優雅——LLVM 4.0 帶來的語法革命

自 Xcode 4.4 (LLVM 4.0) 起,Objective-C 引入字面量語法,讓 NSArray、NSDictionary、NSNumber 的創建像 NSString 一樣簡潔。本文對比新舊寫法,展示現代語法如何減少樣板代碼、提升可讀性、降低出錯率。

一、 NSArray / NSMutableArray

舊寫法 (LLVM 4.0 前)

// 不可變數組:必須以 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"]; // 索引必須已存在

新寫法 (LLVM 4.0+)

// 不可變數組:@[] 字面量,自動推斷類型、計算長度
NSArray *newOne = @[@"1st", @"2nd", @"3th"];

// 取值:下標語法,像 C 數組一樣直觀
NSString *s = newOne[1];

// 可變數組:直接下標賦值,自動擴容、無需預填
NSMutableArray *newMutable = [NSMutableArray array];
newMutable[2] = @"myObject"; // 直接設置索引 2,中間自動補 nil

核心優勢:消除 nil 結尾易漏、objectAtIndex: 冗長、可變數組「必須先有才能改」的反直覺限制。

二、 NSDictionary

舊寫法

NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[o1, o2, o3]
                                                    forKeys:@[k1, k2, k3]];

新寫法

NSDictionary *dict = @{ k1 : o1, k2 : o2, k3 : o3 };

鍵值對直觀映射,順序清晰,編譯期檢查鍵值數量匹配。

三、 NSNumber

舊寫法:各類型對應工廠方法

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) 和字面量形式自動選擇正確構造器。

四、 遷移建議與注意事項

  1. 新項目全量使用新語法:簡潔、安全、現代 IDE 完美補全。
  2. 舊項目增量遷移:修改文件時順手重構,舊語法完全兼容,無需大爆炸式重寫。
  3. 注意 @[] @{} 創建的是不可變對象:需可變請 [NSMutableArray arrayWithArray:@[...]] 或 [NSMutableDictionary dictionaryWithDictionary:@{...}]。
  4. 字面量內對象必須是 Objective-C 對象:不能直接放 int、struct、NULL (需用 [NSNull null])。
  5. 調試時 po 直接支持新語法:LLDB 表達式求值可直接用 @[...] 構造臨時數組。

五、 總結

字面量語法是 Objective-C 向現代語言靠攏的關鍵一步:用聲明式替代命令式,用約定優於配置,用編譯器智能替代手工樣板。擁抱新語法,讓代碼更專注於業務邏輯本身。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved