您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

使用字面量語法讓 Objective-C 程式碼更簡潔

編輯:iOS 相關資訊

一、字面數值

傳統寫法:

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"]);

四、常見的可變物件

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

使用字面量語法建立可變物件時,需加上 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,則會拋出異常。

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