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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With