how can the whole NSMutableArray be filled with the same object(NSString)

65 Views Asked by At

I'm trying this, but it looks like it's not right, are there any options? Thank you

NSMutableArray *copyy = [[NSMutableArray alloc] initWithCapacity:8];
for (int i = 1; i < copyy.count; i++) {
    NSString *str = @"test";
    [copyy addObject:[str copy][i]];
}
1

There are 1 best solutions below

1
Mojtaba Hosseini On BEST ANSWER

You can write a simple category on top of the NSArray like:

@interface NSArray(Repeating)
+ (NSArray*)arrayByRepeatingObject:(id)object times:(NSUInteger)t;
@end

@implementation NSArray(Repeating)
+ (NSArray*)arrayByRepeatingObject:(id)object times:(NSUInteger)t {
    id objects[t];
    for(NSUInteger i=0; i<t; ++i) objects[i] = object;
    return [NSArray arrayWithObjects:objects count:t];
}
@end

so you can build an array by repeating an object like:

NSArray * items = [NSArray arrayByRepeatingObject:@"test" times:8];

Note: if you want a mutable version, just ask for a mutableCopy:

NSMutableArray * mutableItems = items.mutableCopy;