arrayWithObjects ...是否有使用同一对象的快捷方式?

时间:2011-07-15 04:43:25

标签: objective-c cocoa-touch

arrayWithObjects ...是否有使用相同对象“a”或任何对象的快捷方式?

NSMutableArray *kkk = [NSMutableArray arrayWithObjects: @"a", @"a", @"a", @"a", nil];

类似的东西:

NSMutableArray *kkk = [NSMutableArray arrayWithObjects: [repeat: @"a", 4] , nil];

感谢

1 个答案:

答案 0 :(得分:3)

您可以创建一个类别方法,例如:

@interface NSMutableArray (Additions)
 - (void)addObject:(id)object numberOfTimes:(NSUInteger)times;
@end

@implementation NSMutableArray (Additions)
- (void)addObject:(id)object numberOfTimes:(NSUInteger)times
{
    for (NSUInteger i = 0; i < times; i++) {
        [self addObject:object];
    }
}
@end

(根据您的具体情况,您可能希望创建对象的副本,而不是多次将同一对象添加到同一个数组中)

然后你可以这样做:

[array addObject:@"a" numberOfTimes:4];