整个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]];
}
您可以在 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;
我正在尝试这个,但它看起来不对,有什么选择吗?谢谢
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;