PDA

View Full Version : Why does NSArray throw out of bounds errors?




ArtOfWarfare
May 2, 2013, 11:44 PM
It seems to me that NSArray's practice of throwing out of bounds errors is very inconsistent with the behaviors of the other Foundation storage classes.

As far as I know, every other storage class returns nil when it's asked to access something that it doesn't have.

Does anyone know the reasoning behind this decision? It seems like it forces me as the programmer to add in checks everywhere like

NSObject *object;
if (array.count) {
object = array[0];
}

If NSArrays simply behaved the same as every foundation storage class, I could achieve the same thing in a single line of code, with just

NSObject *object = array[0];

Will it silently fail? Perhaps, but I personally really like the ability to send messages to nil. It makes for extremely simple code where when an object doesn't exist nothing should happen, but if it does exist something should be done with it.



lee1210
May 3, 2013, 12:45 AM
Are you talking about NSArray or an actual C array?

I haven't been following changes in OS X SDKs, but from an earlier post it seems like x[y] syntax is available for NSArray now. In any event, the NSRangeException seems reasonable to me for NSArray, and it's been like that for an incredibly long time.

I can't think of a great name, but you could always add a category method:
- (NSObject *) objAt: (NSUInteger) idx
{
if(idx < [self count]) {
return [self objectAtIndex: idx];
} else {
return nil;
}
}

Then you are fine to use:
myValue = [someArray objAt: 100302];
int x = [myValue thatValue];

And care not if there is a real NSObject * at 100302, the array is > than that length, but nil is actually stored there, or the array is shorter than that.

-Lee

ArtOfWarfare
May 3, 2013, 11:18 AM
I'm talking about NSArrays. I've embraced the new syntax.

I guess while I'm at it I could make the method support negative indices to return objects so many spaces from the end.