0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Yes if you do [[[NSMutableArray alloc] initWithCapacity: 100000] count] you will get the answer 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.