Question:
Objective-C memory management - method returns an object?
pop
2007-09-28 06:25:04 UTC
I'm new to memory management as I originally learned java. I have an instance method which creates a new object using alloc and then returns it. My question is how do I release the object I create as after I return the object it loses scope and therefore there is no way to say [object release].
Can I just release the returned object after I have used it?

Thanks very much
Three answers:
anonymous
2007-09-28 09:50:35 UTC
In your code example, the caller will need to call "release" or "autorelease" on the object pointer. Otherwise it will never be cleaned up - memory leak!



Objective-C has specific patterns for memory management. Apple calls it "semi-automatic" memory management.



First, you could code the method to return the object after calling "autorelease" on it. Then it will be valid in the caller, and it will be cleaned up automatically in the next pass through the event loop. If the caller wants to keep it around, they call "retain" on it and keep a pointer to the object around.



Or just return the object. Then the caller is responsible for eventually calling "release" or "autorelease" on the object to make sure it is cleaned up. Document this fact if your method is part of an API that others use!



Also, if you want to cache the object in your method, you can "retain" it and return it to the caller. Because you've incremented the reference count by calling "retain", it will not be deleted if the caller invokes "release" or "autorelease" on it.



In summary, Objective-C requires more thinking and planning than Java for memory management. At least it isn't C or C++! Using the common patterns above will help you avoid memory leaks.
RICHARD B
2007-09-28 06:42:31 UTC
I do C++, there I would return a pointer to the

object declared in the calling method and

passed into the (so going out of scope won't happen

as the allocated memory would be attached to

the pointer which would be available within

to the method to which you returned the pointer).



In C++ the equivalent of 'alloc' is 'new' and in C++

you could then just 'delete' the pointer, after use.
cruppstahl
2007-09-28 06:30:44 UTC
i don't know objective C, but in C you just release the pointer with "free()".



If the pointer goes out of scope, then you have no way of freeing it and you create a memory leak.



valgrind (valgrind.org) is a great tool to detect memory leaks, but it doesn't work on every platform (it runs on MacOS, i think).


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...