Iphone – UIViewController: set self.view to the view or add the view as subview

iphoneuiviewcontroller

I have a question about UIViewController's subview, I created a UIView subclass MainView, which has the exact size of the screen, I wonder which is a better way of adding MainView, consider the following factors:

1 As MainView has same size as the whole screen, the MainView itself may have subviews, but there is no views at the save level as MainView(ie I don't need to add other subviews to self.view).

2 If I use self.view = mainView, do I put the code in loadView(as the viewDidLoad method means the view(self.view) is already loaded)? I see the loadView method is commented out by default, if I add the code to this method, what other code do I need to put together(e.g. initialize other aspects of the application)?

3 If I add mainView via [self addSubview:mainView], are there actually two off screen buffer? One for self.view, one for mainView, both has same size as the screen and one is layered on top of the other(so it wastes memory)?

Thanks a lot!

Best Answer

I'm not sure I completely understand what you're asking, but I'll try to answer a few of the questions you have.

First of all, if you have multiple UIViews on the screen they are all loaded into memory. You have to do -removeFromSuperview and release them to get the memory back.

You can assign your UIView as the UIViewController's view. For example:

MainView *mainView = [[MainView alloc] initWithFrame:CGRectMake(320.0, 480.0)];
self.view = mainView;
[mainView release]; //since the .view property is a retained property

in that case, you have have the view's initialization code in the -init method. Just redefine it like:

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
              //initializations
        }
        return self;
}
Related Topic