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

3

6

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?

Crampton answered 28/3, 2015 at 15:49 Comment(3)
there is not difference performance wise . it is just a difference in syntax between C and Objective CEcru
@Osama in this case that is not C array syntax. It's modern Objective-C syntax for accessing an element from an NSArray.Lozenge
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.Entremets
N
3

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 for setObject:atIndexedSubscript: must be declared with its first argument having some Objective-C pointer type and its second argument having integral type.

Nimbus answered 28/3, 2015 at 15:55 Comment(0)
K
2

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.

Kisumu answered 28/3, 2015 at 16:1 Comment(0)
A
0

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.

Ancier answered 28/3, 2015 at 15:57 Comment(1)
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.Lozenge

© 2022 - 2024 — McMap. All rights reserved.