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

早过忘川 提交于 2019-12-01 14:16:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21923281/what-is-the-difference-in-the-usage-of-the-methods-firstobject-vs-objectatindex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!