Local object scope and memory management in Cocoa
I'm new to Objective-C and Cocoa programming, so i开发者_开发百科n my first sample projects I've always adopted the statement of releasing/autoreleasing all my allocated and copied objects.
But what about local objects allocated inside methods? Let me write some sample code, here is my object interface:
@interface MySampleObject : NSObject {
NSMenu *mySampleMenu;
}
- (void)setupMenu;
@end
Let's now assume that in the setupMenu implementation i create a local menu item to be added to the menu, like follows:
- (void)setupMenu
{
NSMenuItem *myLocalItem = [[NSMenuItem alloc] init];
[myLocalItem setTitle:@"The Title"];
[mySampleMenu addItem:myLocalItem];
[myLocalItem release];
}
The question is: should myLocalItem be released after it has been added to the menu or can I assume that the scope of the object is local so there's no need to manually release since it will be automatically released?
When you create an object like this:
NSMenuItem *myLocalItem = [[NSMenuItem alloc] init];
The object is not in the local stack but on the heap, the only thing that falls off the scope is the pointer, not the object.
Therefore yes, you have to release it.
Nothing will be released automatically (unless you use garbage collection). You should definitely release myLocalItem
here (and MySampleMenu
should retain it).
You should execute the statement [myLocalItem release];
NSMenuItem *myLocalItem = [[NSMenuItem alloc] init]; in this stage myLocalItem will have the retain count as 1.
[mySampleMenu addItem:myLocalItem]; in this stage myLocalItem will have the retain count as 2, since mySampleMenu refer this object(it take the owner ship by adding a retain count to the object)
[myLocalItem release]; since the code is going out of the function, owner ship on the object should be removed. basically you are reducing the retain count by 1.
myLocalItem - The memory allocated to this object will be released when mySampleMenu release the sub menu.
Note: There is nothing like object declared in stack, all object creation happens in heap. There are only different way to handle memory, like 1. Manually handle reference count 2. Add object to autorelease pool then pool decide when to send release message. 3. Enable garbage collection.
Scope has nothing to do with it. Whether an object is due to die (or will die immediately) or not is determined entirely by the messages sent to it.
Review the memory management rules for Cocoa. Those rules are the only things that determine when an object will dealloc.
精彩评论