提问人:juicexxx 提问时间:5/18/2021 最后编辑:Matjuicexxx 更新时间:5/18/2021 访问量:63
如何用相同的对象填充整个NSMutableArray(NSString)
how can the whole NSMutableArray be filled with the same object(NSString)
问:
我正在尝试这个,但看起来不对,有什么选择吗?谢谢
NSMutableArray *copyy = [[NSMutableArray alloc] initWithCapacity:8];
for (int i = 1; i < copyy.count; i++) {
NSString *str = @"test";
[copyy addObject:[str copy][i]];
}
答:
0赞
Mojtaba Hosseini
5/18/2021
#1
你可以在上面写一个简单的类别: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;
评论
0赞
juicexxx
5/18/2021
先生,快速反应。这就是我需要的。
评论