views:

369

answers:

3

This is my init method:

-(id)init{

    self = [super init];
    magicNumber = 8;

    myMagicArray = [[NSMutableArray alloc] initWithCapacity:(magicNumber*magicNumber)];
    NSLog(@"this is the magic Array: %d", [myMagicArray count]);

    return self;
}

This is the .h:

@interface Magic : NSObject {
    NSMutableArray *myMagicArray;
    int magicNumber;

}

The console shows me that number is 0. instead of 64, wt's happen? I already check out this post:

StackOverflow Link: http://stackoverflow.com/questions/633699/nsmutablearray-count-always-returns-zero

+6  A: 

You're confusing capacity with count. The capacity is only the memory space reserved for the array, so when the array expands it doesn't need to take time to allocate memory.

The count is the actual number of items stored in the array.

The -initWithCapacity: method creates an empty array with a hint of how large the array can reach before a memory reallocation. The count increases when you actually -addObject: to the array.


,———.———.———.———————————————————————————————————.
| 4 | 6 | 8 | <—— room for array to expand ———> |
'———'———'———'                                   |
| count = 3                                     |
|                                               |
'——— memory reserved (capacity) of the array ———'
                        > 3
KennyTM
So, how can I get the capacity number? I mean, the 64... in this case....
Tattat
What do you need that for?
zoul
I want fill in the NSMutableArray... ...
Tattat
You don't need the capacity. It's an optimization, and depending on how large a capacity you specify and what internal algorithm NSArray chooses, might actually be ignored. Just add the objects when you get them, using -addObject: or -insertObject:. Different from a CFArray, the capacity of an NSArray isn't a hard limit. It's just a suggestion.If you get your objects in a random order (but with an index number), you could create an array and fill it with [NSNull null] objects using -addObject:, then replace the NSNull with the actual object as you get it.But the latter is rarely needed.
uliwitness
+1  A: 

The "initWithCapacity" method reserves excess capacity so that subsequent insertions don't have to resize the array (until you've overshot the initially reserved capacity), while "count" tells you the actual number of elements in the array (i.e. the number that you've inserted) and not the total capacity available.

Michael Aaron Safyan
A: 

When you init the myMagicArray, you're creating memory space for it... in this case enough memory to hold 64 objects. But you haven't actually added any objects to it yet so the count is 0 until you add an object.

regulus6633
So, can I get the capacity number?
Tattat