访问元素
NSArray *myColors = @[@"Red", @"Green", @"Blue", @"Yellow"];
// Preceding is the preferred equivalent to [NSArray arrayWithObjects:...]
获得单个项目
objectAtIndex:方法提供单个对象。NSArray 中的第一个对象是索引 0.由于 NSArray 可以是同质的(持有不同类型的对象),返回类型是 id(任何对象)。 (可以将 id 分配给任何其他对象类型的变量。)重要的是,NSArrays 只能包含对象。它们不能包含像 int 这样的值。
NSUInteger idx = 2;
NSString *color = [myColors objectAtIndex:idx];
// color now points to the string @"Green"
Clang 提供了更好的下标语法作为其数组文字功能的一部分 :
NSString *color = myColors[idx];
如果传递的索引小于 0 或大于 count - 1,则这两个都抛出异常。
第一件和最后一件
NSString *firstColor = myColors.firstObject;
NSString *lastColor = myColors.lastObject;
firstObject 和 lastObject 是计算属性并返回 nil 而不是为空数组崩溃。对于单个元素数组,它们返回相同的对象。虽然,直到 iOS 4.0 才将 firstObject 方法引入 NSArray。
NSArray *empty = @[]
id notAnObject = empty.firstObject; // Returns `nil`
id kaboom = empty[0]; // Crashes; index out of bounds