I’m just beginning to learn about proper releasing of objects for memory management in iOS. My biggest question is based on the below code.
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"My View Controller";
UIBarButtonItem *item = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(doSomething)];
self.navigationItem.rightBarButtonItem = item;
[item release];
}
Ok, I see that UIBarButtonItem has been created (alloc). Now, it is set to the rightBarButtonItem property in the following line:
self.navigationItem.rightBarButtonItem = item;
Directly after this line, the item gets released.
[item release];
I assume that the item is copied into the rightBarButtonItem but how can I know this happens. If it gets passed by reference, I would have a problem wouldn’t I? Can someone clarify what is going on here and why releasing the object is legal? Much thanks.
This is because the
rightBarButtonItemwas declaredretained. (See the UINavigationItem Documentation)When you declare a property as retained:
You are saying that when you’ll change its value
aNavItem.rightBarButtonItem = aNewItemyou will send a[aNewItem retain]message.Therefore you can safely release it afterwards (as it is retained by the
rightBarButtonItem)For more information, I highly recommend you take a look (monthly just to get used to it until it becomes second nature) at the Apple Memory Management Documentation