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
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
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];
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]);
My ยข2:
NSMutableArray * items = [NSMutableArray new];
while ([items count] < count)
[items addObject: object];
Now, you can use array literal syntax.
NSArray *items = @[@"SO", @"SO", @"SO", @"SO", @"SO"];
You can access each element like items[0];
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.