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 开发者_如何学JAVAreleasing the memory associated with the original object ?
Hope that somebody knowledgable on this can help ...
http://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableArray
You have created an object with alloc
, and you are responsible for the memory of that object. The fact that initWithCapacity:
may return a different chunk of memory than what originally came from the call to alloc
does 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 that alloc
didn't know about and couldn't have allocated.
This is the reason that alloc
and init...
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
Any time you use a method that contains the word alloc
then you are responsible for releasing the memory. For example if you did the following
NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:10];
//Store data into the array here
//Once done you need to release the array
[myArray release];
--Editied post because I meant to type alloc and used init instead.
精彩评论