array[index] 和 [array objectAtIndex:index] 有什么区别?

Whats the difference between array[index] and [array objectAtIndex:index]?

我注意到 array[index][array objectAtIndex:index] 都使用可变数组。有人可以解释它们之间的区别吗?在性能方面,哪个是最佳实践?

None。这是 2-3 年前添加的 clang extensions for objective-c literals 的一部分。

还有:

Array-Style Subscripting

When the subscript operand has an integral type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read or written. When an expression reads an element using an integral index, as in the following example:

NSUInteger idx = ...; id value = object[idx];

It is translated into a call to objectAtIndexedSubscript:

id value = [object objectAtIndexedSubscript:idx]; 

When an expression writes an element using an integral index:

object[idx] = newValue;

it is translated to a call to setObject:atIndexedSubscript:

[object setObject:newValue atIndexedSubscript:idx];

These message sends are then type-checked and performed just like explicit message sends. The method used for objectAtIndexedSubscript: must be declared with an argument of integral type and a return value of some Objective-C object pointer type. The method used for setObject:atIndexedSubscript: must be declared with its first argument having some Objective-C pointer type and its second argument having integral type.

在 Xcode 4.4 之前,objectAtIndex: 是访问数组元素的标准方式。 现在也可以通过方括号下标语法访问它。

从技术上讲,array[index] 语法解析为对数组的 -objectAtIndexedSubscript: 方法的调用。对于 NSArray,这被记录为与 -objectAtIndex:.

相同

下标机制可以扩展到其他 classes(包括你自己的)。理论上,这样的 class 可以为 -objectAtIndexedSubscript:-objectAtIndex: 做一些不同的事情,但那将是糟糕的设计。