开发者

NSMutableArray count method show the NSMutableArray is count 0?

开发者 https://www.devze.com 2022-12-27 00:33 出处:网络
This is my init method: -(id)init{ self = [super init]; magicNumber = 8; myMagicArray = [[NSMutableArray alloc] initWithCapacity:(magicNumber*magicNumber)];

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. inste开发者_如何转开发ad 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号