Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceObjectAtIndex error?

The following code:

NSMutableArray *kkk = [NSMutableArray arrayWithCapacity: 20];
[kkk replaceObjectAtIndex:10 withObject: @"cat"];

yields this

Terminating app due to uncaught exception 'NSRangeException', reason: ' -
[NSMutableArray replaceObjectAtIndex:withObject:]: index 10 beyond bounds for empty array' Call stack at first throw:

like image 731
Kristen Martinson Avatar asked Feb 25 '26 06:02

Kristen Martinson


2 Answers

arrayWithCapacity: allocates the required memory but it doesn't fill the array with objects. nil isn't a valid object to fill the array. So if you need an array with empty objects, you will have to do something like this,

int size = 20;
NSMutableArray *kkk = [NSMutableArray arrayWithCapacity:size];
for ( int i = 0; i < size; i++ ) {
    [kkk addObject:[NSNull null]];
}

Now you can safely replace objects,

[kkk replaceObjectAtIndex:10 withObject: @"cat"];
like image 95
Deepak Danduprolu Avatar answered Mar 01 '26 04:03

Deepak Danduprolu


Getting an array with that capacity does not fill it with elements; it's still an empty array when you try to replace the object at index 10. If you provide more detail as to the context in which this is happening, I can try to suggest a way around the problem.

EDIT: if you must have an array with objects right away, try this:

NSMutableArray *kkk = [NSMutableArray arraywithObjects: @"", @"", @"", @"", nil];

except with 20 @""'s instead of four. Then you get an array of 20 strings. Be sure to put retain on the end of it if you're using it outside the immediate scope, though, since arrayWithObjects returns an autoreleased array.

like image 35
Tom Hamming Avatar answered Mar 01 '26 03:03

Tom Hamming



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!