Patricia
Patricia

Reputation:

How do I handle memory management in this situation?

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?

Upvotes: 0

Views: 134

Answers (2)

diederikh
diederikh

Reputation: 25271

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.

Upvotes: 0

Alex Rozanski
Alex Rozanski

Reputation: 38005

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.

Upvotes: 5

Related Questions