Search code examples
objective-cnsarrayobjective-c-literals

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


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?


Solution

  • 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.