Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ArtOfWarfare

macrumors G3
Original poster
Nov 26, 2007
9,704
6,296
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

Code:
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

Code:
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.
 
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:
Code:
- (NSObject *) objAt: (NSUInteger) idx
{
  if(idx < [self count]) {
    return [self objectAtIndex: idx];
  } else {
    return nil;
  }
}

Then you are fine to use:
Code:
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
 
Last edited by a moderator:
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.