I have a mutable array:
NSMutableArray *array;
Which holds a number of objects.
Which one of the following should i use:
[array replaceObjectAtIndex:10 withObject:anObject];
vs:
array[10] = anObject
in the ARC environment?
Edit:
I assume replaceObjectAtIndex: method would send a release method in Manual Reference Counted environment, whereas direct assignment would not. So would it be confusing the the ARC compiler, if i use direct assignment?
There is a subtle difference between these two approaches.
The Clang documentation explains that array-style subscripting for writing (assignment) translates to a call to setObject:atIndexedSubscript:.
So, from your example, array[10] = anObject; translates to:
[array setObject:anObject atIndexedSubscript:10];
This matters because setObject:atIndexedSubscript: behaves differently than replaceObjectAtIndex:withObject:. Apple's documentation of setObject:atIndexedSubscript: explains the difference (emphasis mine):
If the index is equal to count the element is added to the end of the array, growing the array.
In your example, if array is of size 10, then the expression array[10] = anObject; is valid; it will grow your array and add the object to the end. However, if instead you call [array replaceObjectAtIndex:10 withObject:anObject];, an NSRangeException exception will be thrown.
With regards to which method to use in an ARC environment, I think that's the wrong question to ask. The difference between the two is not ARC-dependent, so your decision should be based on intended behavior (and possibly style).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With