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?
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.
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.
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.
© 2022 - 2024 — McMap. All rights reserved.
[ ]
in the "familiar" (to C programmers) way is relatively new. There are some differences in piddlin' details between this andobjectAtIndex
, but for all intents and purposes they are the same. – Entremets