简体   繁体   English

如何用同一个对象(NSString)填充整个 NSMutableArray

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

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]];
}

You can write a simple category on top of the NSArray like:您可以在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

so you can build an array by repeating an object like:因此您可以通过重复 object 来构建数组,例如:

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

Note: if you want a mutable version, just ask for a mutableCopy :注意:如果你想要一个可变版本,只需要一个mutableCopy

NSMutableArray * mutableItems = items.mutableCopy;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM