I’m an iPhone/Objective-C newbie with an extensive Java background.
I’m learning more about memory management in objective-c and I’m reading Apple’s documentation on Memory Management: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
In the Object Ownership Policy section, it says that you own any object you create via a method that begins with alloc, new or contains copy. Ownership implies that you need to explicitly release the object when you are done with it.
So I’m looking at the NSMutableArray documentation: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
There are two methods that pretty much do the same thing…they both create an array with some initial capacity. One is a class method and the other is an instance method.
+ (id)arrayWithCapacity:(NSUInteger)numItems;
- (id)initWithCapacity:(NSUInteger)numItems;
Now being the lazy Java developer I am, why would I ever choose the instance method over the class method knowing that at some point in time I have to clean up after myself?
I guess I may be missing a fundamental point here…is it simply a matter of determining when the object gets released? autorelease in the class method vs. release in the instance method? I suppose that on a platform with very limited resources (iPhone) I should refrain from using the class method and release the object as soon as I’m done with it?
Thanks!
You will usually choose based on whether or not you are going to own the object for more than the life of the current method (e.g., assign it to some static or directly to an ivar). In that case, you can use the alloc/init method since you know you want to own it already. If you plan to only use it for the scope of the current method, or you are assigning it to something managed like a property, then you would probably use the convenience method.
When you know that you are going to own an object that you are creating, the alloc/init call is always more efficient than the convenience/retain way since the latter is required to basically alloc/init/autorelease the object and then you retain it when it is returned.
You might also use the direct alloc/init methods when you are allocating in a loop and don’t need/want to deal with an autorelease pool.