Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding arrayWithCapacity: method on NSMutableArray

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.

like image 351
Daniel Bastos Avatar asked Dec 11 '22 07:12

Daniel Bastos


1 Answers

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.

like image 151
rmaddy Avatar answered Feb 06 '23 08:02

rmaddy