ArrayWithObjects ... is there a shortcut to use the same object?

arrayWithObjects ... is there a shortcut to use the same object "a" or any object?

NSMutableArray *kkk = [NSMutableArray arrayWithObjects: @"a", @"a", @"a", @"a", nil]; 

sort of:

 NSMutableArray *kkk = [NSMutableArray arrayWithObjects: [repeat: @"a", 4] , nil]; 

thanks

+4
source share
1 answer

You can create a category method from this, for example:

 @interface NSMutableArray (Additions) - (void)addObject:(id)object numberOfTimes:(NSUInteger)times; @end @implementation NSMutableArray (Additions) - (void)addObject:(id)object numberOfTimes:(NSUInteger)times { for (NSUInteger i = 0; i < times; i++) { [self addObject:object]; } } @end 

(Depending on your circumstances, you might want to create a copy of the object, rather than adding the same object several times to the same array)

Then you could just do this:

 [array addObject:@"a" numberOfTimes:4]; 
+3
source

All Articles