What is the difference between the array [index] and [array objectAtIndex: index]?

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

+5
source share
3 answers

Is absent. This part of the clang extensions for objective-c literals added 2-3 years ago.

also:

Array style followers

When the operand index is an integer type, the expression is rewritten to use one of two different selectors, depending on whether the item is being read or written. When an expression reads 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 translates to a call to setObject:atIndexedSubscript:

 [object setObject:newValue atIndexedSubscript:idx]; 

These messages are sent then checked and executed in the same way as an explicit message sends. The method used for objectAtIndexedSubscript: must be declared with an integer argument and the return value of some objective-c object pointer types. The method used for setObject:atIndexedSubscript: must be declared with its first argument having some type of pointer objective-c and its second argument having an integral type.

+3
source

Technically, the syntax of array[index] allows the -objectAtIndexedSubscript: method to be called in an array. For NSArray this is documented as identical to -objectAtIndex:

The signature mechanism can be extended to other classes (including your own). Theoretically, such a class could do something different for -objectAtIndexedSubscript: than for -objectAtIndex: but that would be a bad design.

+2
source

Prior to Xcode 4.4, objectAtIndex: was the standard way to access array elements. Now it can be obtained through the substring syntax with a square bracket.

0
source

Source: https://habr.com/ru/post/1216353/


All Articles