views:

84

answers:

2

I have two classes, a class that handles db connectivity and an entity class. The db class has an instance method called GetEntityByID:(int)entity_id. This method does a simple select statement, and creates an Entity class instance using an init method.

This works fine, however whoever calls GetEntityByID must remember to release it. Since GetEntityByID is not an "init" method, this doesn't seem right. How do I best handle memory management in this situation?

+5  A: 

You can call autorelease in your GetEntityID method on the class to autorelease the instance if it is not otherwise retained.

Since the instantiation of the class is done within your DB connectivity class's method, the object that is returned the instance does not "own" it - your DB connectivity class. As of this, according to convention, you need to memory manage the instance:

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.

If the object sending the GetEntityID method wants to keep the object around, for example if it is to be used as an instance variable, then the returned object can be retained, preventing it from being deallocated at the end of the current event. If it is only being used locally, and doesn't need to be kept around after the current event, then the class doesn't have to do anything; it will be released by the autorelease pool at the end of the current event.

This article explains more about autorelease pools.

Perspx
A: 

To autorelease the object returned in GetEntityID do something like this in GetEntityID:

...  // cool stuff in GetEntityID
return [[entity_id retain] autorelease];
}

Have a look at this really nice article explaining Objective-C memory mangement in more detail.

Diederik Hoogenboom
I don't see any reason for that retain to be there, but autorelease is the correct answer.
Chuck
Yes, that retain] autorelease] is not helpful. The pair of retain and autorelease is used when you expect the original value to be released in the near future and you want to keep the variable's value alive until the autorelease pool flushes.
Jon Hess
I just wanted to be on the safe side as I did not know what was done to the return value in the method.
Diederik Hoogenboom