如何用相同的对象NSString填充整个 NSMutableArray

问题描述

我正在尝试这个,但看起来不对,有什么选择吗?谢谢

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

解决方法

您可以在 NSArray 之上编写一个简单的类别,例如:

@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

所以你可以通过重复一个对象来构建一个数组,比如:

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

注意:如果您想要一个可变版本,只需要求一个 mutableCopy

NSMutableArray * mutableItems = items.mutableCopy;