Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Doesn't NSArray return NULL for nonexistent indexes?

The way I understand it one of the things special about Objective C is that you can send messages to NULL and it will just ignore them instead of crashing.

Why is it that NSArray doesn't just return a NULL object if the index requested is out of bounds instead of causing a NSRangeException?

What I would expect from Objective C and NSArray is the following.

NSArray *array = [NSArray arrayWithObjects:@"Object 1", @"Object 2", @"Object 3", nil];

for (int i = 0; i < 5; i++) {
    NSString *string  = [array objectAtIndex:i];

    if (string) {
        NSLog(@"Object: %@",string);
    }
}

Allowing me to access indexes of the array with don't contain objects and simply returning NULL. Then I can check if the object exists. I can do this in other places such as checking if the object has been instantiated.

NSArray *array;

if (!array) {
    array = [NSArray array];
}

I realize this is a theory based question but I'm curious :)

like image 499
Ryan Poolos Avatar asked May 21 '12 20:05

Ryan Poolos


1 Answers

Messages to nil is a language level feature, not a framework API feature.

That NSArray (and other classes) throw an exception to indicate programmer error is a conscious design decision that was made when the API was designed (~1993). As both Kevin and Richard indicate, nil eats message is not erroneous in anyway whereas out of bounds is very much a case of erroneous input.

Where would you draw the line? Should substringWithRange: accept any old input? How about setObject:atIndex:?

By making NSArray @throw on bounds exceptions for indexOfObject: it makes the API consistent; any index (or range) that is out of bound will @throw.

like image 132
bbum Avatar answered Nov 09 '22 15:11

bbum