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.
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
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.
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