【问题标题】:how can the whole NSMutableArray be filled with the same object(NSString)如何用同一个对象(NSString)填充整个 NSMutableArray
【发布时间】:2021-08-06 23:47:03
【问题描述】:

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

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

【问题讨论】:

标签: objective-c nsarray nsmutablearray


【解决方案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;

【讨论】:

  • 请尽快回复,先生。这就是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 2018-03-19
  • 2018-10-31
相关资源
最近更新 更多