8

How can I add multiple objects to my NSArray? Each object will have the same value.

Ex.

I want the value "SO" added to my array 10 times

Matt S.
  • 13,305
  • 15
  • 73
  • 129

5 Answers5

8

You can initialize the array with a set of objects:

NSString * blah = @"SO";
NSArray * items = [NSArray arrayWithObjects: blah, blah, nil];

or you can use a mutable array and add the objects later:

NSMutableArray * mutableItems = [[NSMutableArray new] autorelease];
for (int i = 0; i < 10; i++)
    [mutableItems addObject:blah];
RedBlueThing
  • 42,006
  • 17
  • 96
  • 122
6

If you don't want to use mutable arrays and also don't want to repeat your identifier N times, utilize that NSArray can be initialized from a C-style array:

@interface NSArray (Foo) 
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t;
@end

@implementation NSArray (Foo)
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t {
    id arr[t];
    for(NSUInteger i=0; i<t; ++i) 
        arr[i] = obj;
    return [NSArray arrayWithObjects:arr count:t];    
}
@end

// ...
NSLog(@"%@", [NSArray arrayByRepeatingObject:@"SO" times:10]);
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
5

My ยข2:

NSMutableArray * items = [NSMutableArray new];
while ([items count] < count)
    [items addObject: object];
esp
  • 7,314
  • 6
  • 49
  • 79
2

Now, you can use array literal syntax.

NSArray *items = @[@"SO", @"SO", @"SO", @"SO", @"SO"];

You can access each element like items[0];

ahuth
  • 1,349
  • 11
  • 15
2

Just add them with initWithObjects: (or whichever method you prefer). An NSArray does not require its objects to be unique, so you can add the same object (or equal objects) multiple times.

mipadi
  • 398,885
  • 90
  • 523
  • 479