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

5 Answers 5

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];
Sign up to request clarification or add additional context in comments.

Comments

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]);

Comments

5

My ¢2:

NSMutableArray * items = [NSMutableArray new];
while ([items count] < count)
    [items addObject: object];

Comments

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.

Comments

2

Now, you can use array literal syntax.

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

You can access each element like items[0];

Comments

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.