Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: why release immediately after creating ui object

Many iPhone code samples (from Apple, etc.) include code like this:

- (void)viewDidLoad {
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

// add the top-most parent view
UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
contentView.backgroundColor = [UIColor blackColor];
self.view = contentView;
[contentView release];

levelView = [[LevelView alloc] initWithFrame:applicationFrame viewController:self];
[self.view addSubview:levelView];

calibrationView = [[CalibrationView alloc] initWithFrame:applicationFrame viewController:self];
}

This snippet is from the BubbleLevel sample project.

My question: why is a release message sent to contentView? We retain a reference to contentView in self.view and we clearly want to use it for the lifetime of the app, not just in this method. Won't calling release cause the view to be released?

like image 737
Matthew Chen Avatar asked Sep 06 '09 19:09

Matthew Chen


2 Answers

Ölbaum is correct in saying that self.view = contentView; will retain your view, which means it won't be deallocated. However, this behavior won't always be the case:

If you look in documentation (or the header) for UIViewController, you'll see that the view property is declared like this:

@property(nonatomic, retain) UIView *view;

This means that whenever the view property is set (foo.view = anotherView or [foo setView:anotherView];), the other view will be retained. If the view property were declared as:

@property(nonatomic, assign) UIView *view;

Then the view would not be retained. It would do a simple pointer assignation into the instance variable. In this case, you would be correct that a subsequent release to contentView would destroy the view, which means the controller would have a stale pointer, which means your app would probably crash.

In other words, when you use properties, make sure you know if they're retain or assign. (If it doesn't say, then it's assign). Then handle your memory management accordingly.

like image 99
Dave DeLong Avatar answered Oct 18 '22 11:10

Dave DeLong


No, because self.view = contentView will retain it. And since you must balance retain and release calls, you need to release it to balance the alloc.

like image 37
Olivier 'Ölbaum' Scherler Avatar answered Oct 18 '22 11:10

Olivier 'Ölbaum' Scherler