Add -[NSArray firstObject] as complement to -lastObject

Originator:quinntaylor
Number:rdar://7725350 Date Originated:2010-03-06
Status:Dupe of 3058939 Resolved:
Product:Foundation Product Version:
Classification:Enhancement Reproducible:Not Applicable
 
NSArray of course has -objectAtIndex: and passing 0 will retrieve the first object. However, if the array contains 0 objects, an NSRangeException is raised (as expected and documented). However, NSArray also has -lastObject, which returns nil if the array is empty, rather than raising an exception. This method is a convenience to (presumably) help avoid querying -count and subtracting one just to find the last index. However, this same logic could be applied to reason for the existence of a -firstObject method as well.

- (id) firstObject {
	return [self count] == 0 ? nil : [self objectAtIndex:0];
}

Such a method would simplify code for getting the first object. I know this is perhaps an extremely minor perceived increase in convenience for developers, but the fact that -lastObject exists but no -firstObject complement does is strange (particularly to Cocoa newcomers), and the difference in behavior between -lastObject and -objectAtIndex: (nil object versus exception) is inconsistent and causes poor impedance matching. Please consider adding this API.

Comments

Duplicate of rdar://3058939

It was filed in September 2002 and now has 7 total dupes.

By quinntaylor at March 8, 2010, 5:45 p.m. (reply...)

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!