In a book, I see the code:
words = [[NSMutableArray alloc] initWithCapacity:[masterWordList count]];
and let’s say [masterWordList count] is 15. And then the code built the array up by using a loop for 10 times:
[words addObject:[masterWordList objectAtIndex:randomNum]];
I wonder why words has to be initWithCapacity… and to 15 slots? Can’t it be 10 or 11 (if a nil is needed at the end… and also, won’t addObject automatically grow the array size? I tried using init instead of initWithCapacity and the code worked too. So can the code in the book be simplified to just init?
initWithCapacity:simply gives the class initializer a “hint” as to the eventual size of the array. That way, it can allocate enough space in advance if you know you’re going to need it. UsinginitWithCapacity:can theoretically provide for better performance because it may mean that the array doesn’t have to reallocate memory (internally) as you add objects to it (I don’t know if it actually does this in the current implementation, but it’s possible). As you’ve guessed, it’s only a hint and usinginitWithCapacity:is entirely optional. Just because you’ve giveninitWithCapacity:a certain size doesn’t mean your array can’t grow to hold more elements than that. Also, callinginitinstead will work just fine.