PDA

View Full Version : Question about Objects created in an Instance Method




klaxamazoo
Sep 3, 2010, 10:21 AM
I know that variables created in an instance method are released after the method is finished, but what about objects created in the method?

For example, what if I allocate and initialize 2 instances of a "Fraction" class in one of my methods to hold some local variables. Do I need to release those instances at the end of my method if I'm no longer using them (i.e. I don't return them)?



SilentPanda
Sep 3, 2010, 10:24 AM
What language? I assume Obj-C but if it's not then the answer is different.

BigJimSlade
Sep 3, 2010, 10:32 AM
If you alloc something, then you own it and are responsible for releasing it.



- (void) myMethod {
NSObject *myObject = [[NSObject alloc] init];

return;
}


This leaks myObject, because the pointer you had to it was stored on the stack, which gets trashed when the method returns. myObject is still on the heap, but you have no way of releasing it because you threw away the pointer.

lee1210
Sep 3, 2010, 10:37 AM
BigJimSlade has the right of it, but you should look over:
http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html

For memory management rules. If you get a pointer to an Object from a method that contains alloc, new or copy, you own it. if you don't release or autorelease it, you leak memory. You must relinquish ownership when you are done with something, and if you aren't returning or storing a pointer that's going to go away at the end of a method, you are definitely done with it, so you must relinquish ownership.

-Lee

SilentPanda
Sep 3, 2010, 10:40 AM
Doesn't Obj-C 2.x do auto-GC if selected? Admittedly I've only learned how to code in Obj-C but haven't done much with it.

Granted it's good practice to release your objects though.

klaxamazoo
Sep 3, 2010, 10:45 AM
Thanks a lot. I was pretty sure that I needed to release any objects I created, but I wanted to make sure.

I'm going through Kochran's "Programming for Objective-C 2.0" so that I can write some small, personal programs to make my research analysis a little easier. It is definitely a good book.

I'll look over the developer documentation on Memory Management.