NSArray: add multiple objects with the same value

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

Ref.

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

+6
objective-c cocoa nsarray
source share
5 answers

You can initialize an array using a set of objects:

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

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

 NSMutableArray * mutableItems = [[NSMutableArray new] autorelease]; for (int i = 0; i < 10; i++) [mutableItems addObject:blah]; 
+8
source share

My ยข 2:

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

If you do not want to use mutable arrays, and also do not want to repeat your identifier N times, use NSArray , which 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]); 
+3
source share

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

+2
source share

Now you can use the array literal syntax.

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

You can access each item, for example items[0];

+2
source share

All Articles