开发者

arrayWithObjects... is there a shortcut for using the same object?

开发者 https://www.devze.com 2023-03-20 22:37 出处:网络
arrayWithObjects... is there a shortcut for using the same object \"a\" or any object? NSMutableArray *kkk = [NSMutableArray arrayWithObjects: @\"a\", @\"a\", @\"a\", @\"a\", nil];

arrayWithObjects... is there a shortcut for using the same object "a" or any object?

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

something like:

NSMutableArray *kkk = [NSMutableArray arrayWithObjec开发者_JS百科ts: [repeat: @"a", 4] , nil];

thanks


You could create a category method out of this, something like:

@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

(Depending on your circumstances, you may want to create a copy of the object instead of adding the same object multiple times to the same array)

Then you could just do this:

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

精彩评论

暂无评论...
验证码 换一张
取 消