Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray count method show the NSMutableArray is count 0?

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: https://stackoverflow.com/questions/633699/nsmutablearray-count-always-returns-zero

like image 454
Tattat Avatar asked Apr 14 '26 00:04

Tattat


2 Answers

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
like image 63
kennytm Avatar answered Apr 15 '26 15:04

kennytm


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.

like image 31
Michael Aaron Safyan Avatar answered Apr 15 '26 16:04

Michael Aaron Safyan



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!