Does NSMutableArray's counting method show that NSMutableArray has a value of 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 .h:

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

}

The console shows me that the number is 0. instead of 64, huh? I am already checking this post:

stack overflow

+3
source share
4 answers

You confuse capacity with the bill. Capacity is just the memory space reserved for the array, so when the array expands, it does not take time to allocate memory.

A counter is the actual number of elements stored in an array.

-initWithCapacity: , . , -addObject: .


,———.———.———.———————————————————————————————————.
| 4 | 6 | 8 | <—— room for array to expand ———> |
'———'———'———'                                   |
| count = 3                                     |
|                                               |
'——— memory reserved (capacity) of the array ———'
                        > 3
+8

"initWithCapacity" , ( , ), "count" ( .. , ), .

+1

myMagicArray, ... 64 . , 0, .

0

You cannot access the property capacity, and it does not represent a filled size (as kennytm has eloquently described).

One approach may be to get the class from NSMutableArrayand hook the method initWithCapacity, write initialCapacityand then collapse it in the property. But if you're in a hurry, you can use this simple method below:

Create a function:

NSMutableArray* createArrayWithSize(NSUInteger number)
{
    NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:number];
    for( NSUInteger i=0;i<number; i++ )
    {
        array[i]=[NSNull null];
    }
    return array;
}

Then initialize your NSMutableArray as follows.

myMagicArray = createArrayWithSize(10);

[myMagicArray count] now it will be 10.

0
source

Source: https://habr.com/ru/post/1740645/


All Articles