Tattat
Tattat

Reputation: 15778

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

Upvotes: 3

Views: 5529

Answers (4)

GilesDMiddleton
GilesDMiddleton

Reputation: 2320

You can't access the capacity property, and it doesn't represent populated size (as eloquently described by kennytm).

One approach might be to derive a class from NSMutableArray and intercept the initWithCapacity method, to record the initialCapacity and then churn it out in a property. But if you're in a rush, 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 initialise your NSMutableArray as follows.

myMagicArray = createArrayWithSize(10);

[myMagicArray count] will now be 10.

Upvotes: 0

kennytm
kennytm

Reputation: 523184

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

Upvotes: 8

regulus6633
regulus6633

Reputation: 19032

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.

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95459

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.

Upvotes: 1

Related Questions