2010-09-24 49 views

回答

1

答案是NSMutableArray總是以零的大小開始。如果你想這樣做,你可以這樣做:

NSMutableArray* anArray = [NSMutableArray arrayWithSize: 2000]; 
[anArray replaceObjectAtIndex: 1999 withObject: foo]; 

你需要預先填充NSNull對象的數組,

@implementation NSArray(MyArrayCategory) 

+(NSMutableArray*) arrayWithSize: (NSUInteger) size 
{ 
    NSMutableArray* ret = [[NSMutableArray alloc] initWithCapacity: size]; 
    for (size_t i = 0 ; i < size ; i++) 
    { 
     [ret addObject: [NSNull null]]; 
    } 
    return [ret autorelease]; 
} 

@end 

編輯:一些進一步澄清:

-initWithCapacity:提供了一個關於你有多大想的陣列可能是暗示的運行時間。運行時間沒有義務直接實際分配該內存量。

NSMutableArray* foo = [[NSMutableArray alloc] initWithCapacity: 1000000]; 
    NSLog(@"foo count = %ld", (long) [foo count]); 

將記錄的0

-initWithCapacity:計數不限制數組的大小:

NSMutableArray* foo = [[NSMutableArray alloc] initWithCapacity: 1]; 
    [foo addObject: @"one"]; 
    [foo addObject: @"two"]; 

不會導致錯誤。

+0

謝謝你的回覆。我有一個關於你的解釋的問題。在開始時,objective-c中的所有NSMutableArray的大小是否爲0? – Questions 2010-09-24 10:13:34

+0

是的,如果你做了[[[[[[NSMutableArray alloc] initWithCapacity:100000] count]'你會得到答案0。 – JeremyP 2010-09-24 10:55:38