Question

I'm having a hard time trying to understand a method in the Objective-C's NSMutableArray class. I created an array using the arrayWithCapacity: static method of this class, just like this:

NSMutableArray * myArray = [NSMutableArray arrayWithCapacity: 10];

Then I tried to access an element inside the array:

id myVariable = myArray[5];

And that's what I get:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds for empty array'

Why does it happen? Did I misunderstand anything about the method description?

Thanks for the help.

Was it helpful?

Solution

Using arrayWithCapacity:10 means that internally, the array will set itself up to hold 10 objects. But it still has no objects in it.

Normally, an empty array is created and setup to hold just a few objects. As you add more and more objects, the internal array needs to be resized. This means more memory needs to be malloced, then the old objects are moved to the new memory, and the old memory is cleaned up.

If you know the array will hold X number of objects, using arrayWithCapacity allows the array to be more efficient. You can still add more objects but then the efficiency will be lost.

All of this aside, you can't access an array index beyond its current count. Since the count is 0 at first, you can't access any objects. You need to add objects before you can access them.

OTHER TIPS

You have initialised array like :

NSMutableArray * myArray = [NSMutableArray arrayWithCapacity: 10];

this means you can add up to 10 objects into the array . And you are accessing the sixth object of the array :

id myVariable = myArray[5];

I dont know how you are adding the objects into the array but from the error it seems like your array dont have the objects and your are trying to access sixth index of the empty array . Try to add some objects first .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top