-objectAtIndex: in Cocoa Uncanny Valley

Objective-C:

NSLog(@"%@", [[NSArray arrayWithObjects:@"a",@"b",nil] objectAtIndex:-1]);
// => NSRangeException: *** -[NSCFArray objectAtIndex:]: index (-1 (or possibly larger)) beyond bounds (2)

Bit-pattern-wise, (int32_t)-1 == (uint32_t)0xFFFFFFFF, so that innocent-but-invalid -1 gets interpreted as ULONG_MAX.

ULONG_MAX is waaaay outside the bounds of our 2-element array, so an invalid index exception gets correctly thrown.

But things can get different in Cocoa Uncanny Valley:

JSCocoa/JSTalk:

[[NSArray arrayWithObjects:@"a", @"b", nil] objectAtIndex:-1];
// => @"a"

Somewhere in JSCocoa’s machinery -1 morphs into zero, and the first element is retrieved sans exception. Ouchie.

Objective-J:

[[CPArray arrayWithObjects:@"a",@"b",nil] objectAtIndex:-1];
// => undefined

Cappuccino’s CPArray doesn’t throw an exception, just quietly returns nothing. I wish it barked like NSArray.

MacRuby:

NSArray.arrayWithObjects('a','b', nil).objectAtIndex(-1)
# => probably NSRangeException

My version of MacRuby (0.5b1 I think) crashes inside rb_vm_print_current_exception(), so I think it’s trying to sputter out NSRangeException.

Nu:

((NSArray arrayWithList:`("a" "b")) objectAtIndex:-1)
;; => NSRangeException: *** -[NSCFArray objectAtIndex:]: index (-1 (or possibly larger)) beyond bounds (2)

Not surprised, Nu is in perfect mesh.

Dec 2 2009