Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference in the usage of the methods firstObject vs objectAtIndex:0?

Tags:

ios

nsarray

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.

like image 384
Keale Avatar asked Feb 21 '14 01:02

Keale


People also ask

What is difference between NSArray and NSMutableArray?

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.

What is NSArray in swift?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.


1 Answers

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.

like image 196
virindh Avatar answered Nov 02 '22 22:11

virindh