Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 876
Boon Avatar asked Jul 01 '09 22:07

Boon


People also ask

How do I create an NSArray in Objective C?

Creating an Array ObjectThe NSArray class contains a class method named arrayWithObjects that can be called upon to create a new array object and initialize it with elements. For example: NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

What is difference between NSArray and NSMutableArray?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays.

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

How do you declare an array in Objective C?

To declare an array in Objective-C, we use the following syntax. type arrayName [ arraySize ]; type defines the data type of the array elements. type can be any valid Objective-C data type.


1 Answers

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];
like image 144
mxcl Avatar answered Sep 19 '22 20:09

mxcl