开发者

Setting Up the Default State of an Array

I have an array I need to construct with a pre-determined number of zero-value objects that will be changed later.

I am doing it this way:

NSMutableArray *myArray = [[[NSMutableArray alloc] initWithObjects:
    [NSNumber numberWithInt:0], 
    [NSNumber numberWithInt:0], 
    [NSNumber numberWithInt:0],
    . . .
    nil]
    autorelease];

However, I've got 20 zero-value placeholders I need to create, so I think about doing it开发者_如何学JAVA this way:

NSMutableArray *myArray = [[[NSMutableArray alloc] init] autorelease];

for (NSUInteger x = 0; x < 20; ++x) {
    [myArray addObject:[NSNumber numberWithInt:0]];
}

In the first example, nil is placed at the end of the array, in the second, it isn't. Does it make a difference? Also, is there a benefit in one way of doing this over the other?


No, nil is not placed at the end of the array. As a matter of fact, nil is not a valid member of a collection in Cocoa. It is just used as the delimiter of the argument list here. There is no practical difference between the two variants you posted (besides the autorelease you are using in the first and omitting in the second example, of course).

I suspect the first one to be slightly faster (and you could possibly optimize the second one by using initWithCapacity:) but it won't make a noticeable difference given the small size of the array.

Note that you could also use [NSNull null] to indicate a placeholder object in a collection. It depends on your specific use case if that would be better than using the number 0.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜