问题描述
今天我已经使用firstObject和objectAtIndex:0进行了测试。如果数组的大小为0,则使用前者不会导致崩溃,而后者会导致崩溃。所以我认为使用firstObject比使用objectAtIndex:0更好。但是在objectAtIndex上使用firstObject是否存在缺陷:0?
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.
推荐答案
有一个 键 的区别。如果没有,则使用 firstObject
返回 nil
。如果没有对象,使用 objectAtIndex:0
将使您的应用程序崩溃(抛出异常)。从用户体验的角度来看,崩溃是高度提倡的,所以它更安全使用 firstObject
。
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
.
但是 最大的陷阱: firstObject
自iOS 4开始提供,但在iOS 7之前是一个私有API。
BUT the biggest pitfall: firstObject
has been available since iOS 4, but was a private API until iOS 7.
这篇关于firstObject vs objectAtIndex:0的方法用法有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!