Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

klaxamazoo

macrumors 6502
Original poster
Sep 8, 2006
438
0
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)?
 
If you alloc something, then you own it and are responsible for releasing it.

Code:
- (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.
 
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
 
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.
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.