PDA

View Full Version : noob memory management question




thevibesman
Dec 16, 2008, 01:34 PM
I'm fairly new to objective-c, so I'm guessing the answer to this question is so obvious that I couldn't find the answer.

Do the memory management rules (i.e. no garbage collection) just refer to the memory used by objective-c objects? What I'm wondering is that in some of my lower level code I'm writing in C, do the normal stack/heap rules apply (i.e. memory on the stack is automatically freed with the function is finished) or do I need to manually manage all my C memory too?

Thanks



xsmasher
Dec 16, 2008, 04:31 PM
I'm fairly new to objective-c, so I'm guessing the answer to this question is so obvious that I couldn't find the answer.

Do the memory management rules (i.e. no garbage collection) just refer to the memory used by objective-c objects? What I'm wondering is that in some of my lower level code I'm writing in C, do the normal stack/heap rules apply (i.e. memory on the stack is automatically freed with the function is finished) or do I need to manually manage all my C memory too?

Thanks

You mean do you need to release your ints, floats, and structs? No, you don't. Regular C memory management works same as always.

What isn't implemented on the iPhone is Java-style automatic garbage collection, where objects with no references are cleaned up by the system.
You need to retain and release your objects (anything inherited from NSObject) so that they get deallocated when the reference count hits zero.

There is also an "autorelease" facility on the iphone, but it's a convenient compliment to retain/release, not a replacement. (Anything set to "autorelease" will get released once at the end of the current event - you can't set everything to autorelease and forget it.)

SqueegyX
Dec 16, 2008, 04:56 PM
Objects need to be released, primitive values do not. Release instances of Objective-C classes, but floats, ints, etc will be automatically freed as soon as their declared scope is lost (such as the end of the method in which they were declared).

You also do not need to released instance variables unless they are instances of classes.

thevibesman
Dec 16, 2008, 06:32 PM
Thanks guys, that is what I thought but since I hadn't seen it explicitly stated I thought I should be sure.