NSMutableArray does not raise NSRangeException when trying to set an element at the end of the array

Maybe I'm doing something obviously wrong here, but why does this code behave like this:

NSMutableArray<NSNumber*> *a = @[@(0), @(0), @(0)].mutableCopy;

a[3] = @(1); // works, but why?
a[4] = @(1); // also works

NSMutableArray<NSNumber*> *b = @[@(0), @(0), @(0)].mutableCopy;

b[4] = @(1); // crash 💥 index 4 beyond bounds [0 .. 2]

The documentation says that:

If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.

https://developer.apple.com/documentation/foundation/nsmutablearray/1460093-setobject

Replies

The code shown for your array named a should work. You have:

NSMutableArray<NSNumber*> *a = @[@(0), @(0), @(0)].mutableCopy;

a[3] = @(1); // works, but why?
a[4] = @(1); // also works

So you have three NSNumbers in an array at index 0, 1, 2.

Then you add another number at index 3, which would be the same thing as doing this:

[a addObject:@(1)];

I could be wrong but I believe the line in the documentation below is wrong:

If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.

I think it should say:

If index is beyond the end of the array (that is, if index is greater than the value returned by count), an NSRangeException is raised.

The documentation also says:

Replaces the object at the index with the new object, possibly adding the object.

You probably should file a bug. Either the documentation or the code is wrong but I believe it is the documentation.

You probably should file a bug.

Please do.

Either the documentation or the code is wrong but I believe it is the documentation.

Agreed.

Oh, and please post your bug number, just for the record.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks for taking the time to answer. Here is the bug number: FB9952056.

Add a Comment