Creating an NSArray initialized with count N, all of the same object

cocoa, initialization, nsarray, objective-c

Solution

The tightest code I've been able to write for this is:

id numbers[n];
for (int x = 0; x < n; ++x)
    numbers[x] = [NSNumber numberWithInt:0];
id array = [NSArray arrayWithObjects:numbers count:n];

This works because you can create runtime length determined C-arrays with C99 which Xcode uses by default.

If they are all the same value, you could also use memset (though the cast to int is naughty):

id numbers[n];
memset(numbers, (int)[NSNumber numberWithInt:0], n);
id array = [NSArray arrayWithObjects:numbers count:n];

If you know how many objects you need, then this code should work, though I haven't tested it:

id array = [NSArray arrayWithObjects:(id[5]){[NSNumber numberWithInt:0]} count:5];

Problem

I want to create an NSArray with objects of the same value (say NSNumber all initialized to 1) but the count is based on another variable. There doesn't seem to be a way to do this with any of the intializers for NSArray except for one that deals with C-style array. Any idea if there is a short way to do this? This is what I am looking for: ``` NSArray *array = [[NSArray alloc] initWithObject:[NSNumber numberWithInt:0] count:anIntVariable]; ``` NSNumber is just one example here, it could essentially be any NSObject.

Original source