views:

229

answers:

5

As far as I know, only the "convenience" methods return created objects with an -autorelease, so that the receiver is not responsible for the memory of that object. But because Apple says that when you use a method that has a name consisting of "new", "alloc", "create" or "copy", you're responsible for releasing the object that method returns, I think that these methods should not -autorelease these objects. Otherwise they would be "convenient" and the receiver would not be responsible at all as long as he does not -retain the received object. Did I get that right?

+1  A: 

That is correct. The official word is at Apple's Developer Site This is for CoreFoundation, but it applies to Cocoa as well.

Mark Thalman
+1  A: 

Almost.

I don't believe "create" is one of the defined keywords from Apple guidelines.

Otherwise your logic is correct. The object that method returns is not retained by that method's class.

NSObject *obj = [[someClass alloc]init]; // you are responsible
NSObject *obj = [someClass someConvenientMethod]; // the object is auto-released, you do not own this object
Jab
create is actually a keyword, but it's used in CoreFoundation rather than Cocoa, where it's alloc.
Jason Coco
+5  A: 

The answer to the question in the title is yes, however:

only the "convenience" methods return created objects with an -autorelease

That is definitely not true. Any method that does not have one of the marker words (or have specific documentation saying otherwise) is assumed to return an object that you do not have a retaining reference to. Convenience constructors certainly fall into that group, but so do most other methods in Cocoa.

Returning an object that you are not responsible for releasing is the rule in Cocoa, not the exception.

This is all very clearly spelled out in Apple's online documentation about memory management in Cocoa; you should really read those documents thoroughly. Many of the questions you are asking on this site are answered there, and it's the definitive source.

smorgan
+3  A: 

The rule of thumb is that you own (and therefore must release) any object that you

  • alloc (using a method starting "alloc" or "new"*)
  • copy (using any method containing the word copy)
  • retain explicitly yourself

*new combines an alloc and an init into one method.

Convenience methods return objects that are autoreleased. These are valid for the scope of the method you receive them in and can be passed back to a calling method (generally). If you want to keep them longer than that, you need to retain them.

Jane Sales
A: 

Check out Apple's documentation on Object Ownership and Disposal

harveyswik