集裝箱下標

在現代 Objective C 語法中,你可以使用容器下標從 NSArrayNSDictionary 容器中獲取值。

舊方式:

NSObject *object1 = [array objectAtIndex:1];
NSObject *object2 = [dictionary objectForKey:@"Value"];

現代方式:

NSObject *object1 = array[1];
NSObject *object2 = dictionary[@"Value"];

你還可以以更清晰的方式將物件插入到陣列中併為字典中的鍵設定物件:

舊方式:

// replacing at specific index
[mutableArray replaceObjectAtIndex:1 withObject:@"NewValue"];
// adding a new value to the end
[mutableArray addObject:@"NewValue"];

[mutableDictionary setObject:@"NewValue" forKey:@"NewKey"];

現代方式:

mutableArray[1] = @"NewValue";
mutableArray[[mutableArray count]] = @"NewValue";

mutableDictionary[@"NewKey"] = @"NewValue";