0

I write a simple ios app. All of my views are created programmatically. Here is some code

rootViewController.m

-(void)loadView
{
  UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
  self.view = view;
  self.view.backgroundColor = [UIColor greyColor];
}

In appDelegate I add rootViewController view to the window and everything work fine. But if expression

self.view = view

is removed rootViewController is not loaded in window. Why is this happening ?

1 Answer 1

4

Because if you don't set the view property of the view controller then the view controller's view is nil and a nil view means a blank screen.

What would you expect to happen if you try to display a view controller with a nil view?

Normally view controllers create their own empty view (or load it from a nib file) when you first reference their view property, but since you are overriding the loadView method, you have to set the view yourself.

Your code may be easier to understand if written like this - the view variable and view property having the same name may be the source of your confusion:

-(void)loadView
{
  self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
  self.view.backgroundColor = [UIColor grayColor];
}

Incidentally, if you aren't using ARC, you need to autorelease the UIView above before you assign it to the self.view or you'll have a leak.

Sign up to request clarification or add additional context in comments.

1 Comment

Wanted to point out that greyColor wasn't working for me but grayColor did. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.