Why does NSArray throw out of bounds errors?

Discussion in 'Mac Programming' started by ArtOfWarfare, May 2, 2013.

  1. macrumors 603

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #1
    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.
     
  2. lee1210, May 2, 2013
    Last edited by a moderator: May 3, 2013

    macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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
     
  3. thread starter macrumors 603

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #3
    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.
     

Share This Page