5

in C I can simply declare an array like this:

int array[500]; 

to declare an array of size 500 which can then be filled later. Is it possibel to do the same thing in NSArray? I understand for the NSMutableArray there is the arrayWithCapacity class method to "create" and empty array (or at least declare the array to be filled later). Is there a way to do something similar for NSArray, since I know the exact size of my array I want to fill in the contents later in a "for" loop.

Thanks

1 Answer 1

2

Technically, int array[500]; does not create an empty array - it creates an array full of zeros. Since NSArrays is immutable, you do need to use NSMutableArray if you'd like to be able to populate it later.

You can make an array with a specific capacity, and then put objects into it, like this:

NSMutableArray *array = [NSMutableArray arrayWithCapacity:500];
for (int i = 0 ; i != 500 ; i++) {
     [array addObject:@(i)];
}

Since NSMutableArray is an NSArray, you can create it in a method as NSMutableArray*, and then return it as NSArray* to the callers.

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

2 Comments

This answer has an issue. As stated in the documentation for [NSArray arrayWithObjects:count:]: "count is the number of values from the objects C array to include in the new array. This number will be the count of the new array. It must not be negative or greater than the number of elements in objects."
@DavePeck OMG, I cannot believe nobody has noticed this before! Thanks for the comment!

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.