您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

用字面量語法讓 iOS 程式碼更簡潔優雅

編輯:iOS 開發綜合

Objective-C 提供了字面量(Literal)語法,能大幅簡化物件建立與存取的寫法,讓程式碼更精簡易讀。以下逐一說明。

一、字面數值

傳統寫法:

NSNumber *someNumber = [NSNumber numberWithDouble:3.4];
NSLog(@"the value is %@", someNumber);

字面量寫法:

NSNumber *a = @21.3;
NSNumber *b = @32;
NSLog(@"the value is %@", a);
NSLog(@"the value is %@", b);

二、字面量陣列

傳統寫法:

NSArray *arr = [NSArray arrayWithObjects:@"hello", @"richard", @"yang", nil];
NSLog(@"the first object is %@", [arr objectAtIndex:0]);

字面量寫法:

NSArray *arr1 = @[@"hello", @"richard", @"yang"];
NSLog(@"the first object is %@", arr1[1]);

注意:用字面量語法建立陣列時,若有元素為 nil 會拋出異常;而用 arrayWithObjects 建立時,nil 之前的資料仍可正確建立。

三、字面量字典

傳統寫法:

NSDictionary *personDic = [NSDictionary dictionaryWithObjectsAndKeys:@"richard", @"name", @"001", @"num", nil];
NSLog(@"name is %@", [personDic valueForKey:@"name"]);

字面量寫法:

NSDictionary *personDic = @{@"name": @"richard", @"num": @"001"};
NSLog(@"the name is %@", personDic[@"name"]);

四、建立可變物件

用字面量語法建立可變物件時,需加上 mutableCopy:

NSMutableArray *arr1 = [@[@"hello", @"richard", @"yang"] mutableCopy];

五、用字面量語法修改值

NSMutableArray *arr1 = [@[@"hello", @"richard", @"yang"] mutableCopy];
NSLog(@"the first value is %@", arr1[0]);
arr1[0] = @"andy";
NSLog(@"the first value is %@", arr1[0]);

六、總結

1. 用字面量語法建立物件,簡潔明快;
2. 透過取下標操作存取陣列、取 key 操作存取字典;
3. 用字面量語法建立陣列或字典時,若值中有 nil 會拋出異常。

善用字面量語法,不僅讓程式碼更短,也更貼近直覺,是提升 Objective-C 可讀性的好習慣。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved