It’s about the instance method of NSMutableArray “initWithCapacity”.
From documentation, the Return Value is described as:
Return Value An array initialized with enough memory to hold numItems objects. The returned object might be different than the original receiver.
There seems to be a typo at “different than”, my guess is it should be “different from”. And also if the returned object is indeed different from the original, do we have to worry about releasing the memory associated with the original object ?
Hope that somebody knowledgable on this can help …
You have created an object with
alloc, and you are responsible for the memory of that object. The fact thatinitWithCapacity:may return a different chunk of memory than what originally came from the call toallocdoes not change that.Initializer methods in Cocoa are allowed to deallocate the instance they are passed and create a new one to be returned. In this case, it’s necessary for
initWithCapacity:to do so, since you’re actually asking it to reserve more memory thatallocdidn’t know about and couldn’t have allocated.This is the reason that
allocandinit...should always be paired:[[NSMutableArray alloc] initWithCapacity:10]Regarding
initWithCapacity:specifically, bbum (who knows of what he speaks — Apple engineer) says that it’s usually unecessary. It does not preclude you from expanding the array past the specified size. All it does is potentially allow the array to do some initial optimization*; unless you’ve measured and it makes a significant difference, it’s probably not necessary.*See Objective-c NSArray init versus initWithCapacity:0