I noticed that both array[index]
and [array objectAtIndex:index]
work with mutable arrays. Could someone explain the difference between them? in terms of performance, and which one is the best practice?

- 63,694
- 13
- 151
- 195

- 166
- 1
- 13
-
1there is not difference performance wise . it is just a difference in syntax between C and Objective C – Usama Sadiq Mar 28 '15 at 15:53
-
1@Osama in this case that is not C array syntax. It's modern Objective-C syntax for accessing an element from an NSArray. – rmaddy Mar 28 '15 at 15:59
-
The notation using `[ ]` in the "familiar" (to C programmers) way is relatively new. There are some differences in piddlin' details between this and `objectAtIndex`, but for all intents and purposes they are the same. – Hot Licks Mar 28 '15 at 17:50
3 Answers
None. That's part of the clang extensions for objective-c literals, added 2-3 years ago.
Also:
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 forsetObject:atIndexedSubscript:
must be declared with its first argument having some Objective-C pointer type and its second argument having integral type.

- 19,081
- 8
- 48
- 55
Technically, the array[index]
syntax resolves into a call of the -objectAtIndexedSubscript:
method on the array. For NSArray
, this is documented as being identical to -objectAtIndex:
.
The subscripting mechanism can be extended to other classes (including your own). In theory, such a class could do something different for -objectAtIndexedSubscript:
than for -objectAtIndex:
, but that would be poor design.

- 88,520
- 7
- 116
- 154
Prior to Xcode 4.4, objectAtIndex: was the standard way to access array elements. Now it can be accessed through the square-bracket subscripting syntax aswell.

- 2,075
- 15
- 13
-
It had nothing to with Xcode. It has to do with the version of clang - the Objective-C compiler. And it's not about standard array access. It's about access to objects in an NSArray. – rmaddy Mar 28 '15 at 16:01