Today I have tested using firstObject and objectAtIndex:0. If the array has the size of 0, using the former does not cause a crash while the latter causes a crash. So I'm thinking that it's better to use firstObject than objectAtIndex:0. But are there pitfalls in using firstObject over objectAtIndex:0?
I have also been reading through the NSArray documentation and I am surprised and wondering why they did not mention this fact on the documentation.
There is one key difference. Using firstObject
returns nil
if there is none. Using objectAtIndex:0
will crash your app(throws an exception) if there is no object there.From a user experience perspective, crashing is highly advocated against, so it is safer to use firstObject
.
BUT the biggest pitfall: firstObject
has been available since iOS 4, but was a private API until iOS 7.