Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using Autoreleased Constructors

From: namedConstructor.m

I said in the last section that objects created with +alloc have a retain count of one. In fact, all objects are created with a retain count of one, but objects created with a named constructor, such as +stringWithFormat: or +array, are also autoreleased.

If you create an object with one of these mechanisms, you must send it a -retain message if you want to keep it. If you don’t, it will be collected later when the autorelease pool is destroyed.

This is a convention that is important to observe in your own classes. If someone creates an instance of one of your classes with a named constructor, he will expect not to have to release it. A typical named constructor would look something like the one at the start of this section.

Note that, because this is a class method, the self object will be the class. By sending the +alloc message to self rather than to the class name, this method can work with subclasses automatically.

With ARC, these conventions are formalized in method families. Methods that begin alloc, new, copy, or mutableCopy return an owning reference, a reference that must be released if not stored. Other methods return a non-owning reference, one that has either been autoreleased or is stored somewhere else with a guarantee that it will not be released.

  • + Share This
  • 🔖 Save To Your Account