views:

67

answers:

1

Hi, everyone,

I want to ask the size of the NSMutable Array can be 2000? If not, is it possible to open an array to store 2000 elements. The elements is the user-defined object. Thank you.

+1  A: 

The answer is that an NSMutableArray always starts with a size of zero. If you want it to be so you can do something like this:

NSMutableArray* anArray = [NSMutableArray arrayWithSize: 2000];
[anArray replaceObjectAtIndex: 1999 withObject: foo];

you need to prefill the array with NSNull objects e.g.

@implementation NSArray(MyArrayCategory)

+(NSMutableArray*) arrayWithSize: (NSUInteger) size
{
    NSMutableArray* ret = [[NSMutableArray alloc] initWithCapacity: size];
    for (size_t i = 0 ; i < size ; i++)
    {
        [ret addObject: [NSNull null]];
    }
    return [ret autorelease];
}

@end

Edit: some further clarification:

-initWithCapacity: provides a hint to the run time about how big you think the array might be. The run time is under no obligation to actually allocate that amount of memory straight away.

    NSMutableArray* foo = [[NSMutableArray alloc] initWithCapacity: 1000000];
    NSLog(@"foo count = %ld", (long) [foo count]);

will log a count of 0.

-initWithCapacity: does not limit the size of an array:

    NSMutableArray* foo = [[NSMutableArray alloc] initWithCapacity: 1];
    [foo addObject: @"one"];
    [foo addObject: @"two"];

doesn't cause an error.

JeremyP
@JeremyP, thank you for your reply. And I have a question about your explanation. Is all the NSMutableArray in the objective-c is size of 0 in the begining?
Questions
Yes if you do `[[[NSMutableArray alloc] initWithCapacity: 100000] count]` you will get the answer 0.
JeremyP