Kristen Martinson
Kristen Martinson

Reputation: 1869

arrayWithObjects... is there a shortcut for using the same object?

arrayWithObjects... is there a shortcut for using the same object "a" or any object?

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

something like:

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

thanks

Upvotes: 4

Views: 336

Answers (1)

indragie
indragie

Reputation: 18122

You could create a category method out of this, something like:

@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 may want to create a copy of the object instead of adding the same object multiple times to the same array)

Then you could just do this:

[array addObject:@"a" numberOfTimes:4];

Upvotes: 3

Related Questions