I’m new to Objective-C and Cocoa programming, so in 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:
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.