R – Why does a Convencience Constructor or Object Factory have to care about releasing the Object

autoreleasememory-managementobjective c

Actually, if you use a method with "new", "create", "alloc" or "copy" in it's name, then you are responsible for releasing the object that is returned to you. BUT: Why do these methods make an call to -autorelease? Wouldn't this result in "over-releasing" the object?

Lets say I get that object from such a method, and then I call -release on that. The object is in the Autorelease Pool and has a reference count of 0. What would happen next, when the Autorelease Pool is released?

Best Answer

Convenience constructors don't have any of those words in their names (e.g., [NSMutableArray array]), so by convention they return autoreleased objects. Methods that do have one of the words that indicate they return a retained object don't call autorelease, so that part of the premise of your question is incorrect.

If you release objects returned from a convenience constructor yourself (without having explicitly retained them) then they will be over-released, and your application will probably crash.