0

New to iOS dev. Kindly correct me if i am wrong?

I have a UIWindow, and rootviewcontroller is :

@interface ViewController : UIViewController
{
IBOutlet UIButton *but;
}

@property (nonatomic, strong) UIButton  *but;
-(IBAction) butButtonPressed;

@end

ie: If i make this Viewcontroller as a root view controller, the UIView that is available in the ViewController is displayed. Understood.

I have created a new class inherited from UIViewController, and along with its .xib file.

So xib file name is : view1.xib,

My Objective is to display this view when the button is pressed.

Now i have created a button and button press invokes butButtonPressed. Inside of butButtonPressed, i did the following.

  myViewController *vcontroler = [[ViewController alloc] initWithNibName:@"view1" bundle:nil];
    [self.view.window addSubview:vcontroler.view];

Application crashes. What am i doing wrong ? Kindly point out.

Whoami
  • 13,930
  • 19
  • 84
  • 140

1 Answers1

1

This...

[self.view.window addSubview:vcontroler.view];

...is a really bad strategy (and I seriously wish I knew where people are finding it as a way of showing views). If you create a view controller, you should use it rather than just treating it as a temporary container that you can rip views out of.

If you want vcontroler to look like a child of your first controller (and you have a UINavigationController), use pushViewController:animated:. Otherwise you can show it as modal with presentModalViewController:animated:.

If you only want to add a view to the existing display, put the view in ViewController's hierarchy and show/hide it.

If you absolutely must have it as a sub-controller of ViewController then you need to keep a reference to it and manage its lifecycle inside the owning controller.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
  • Phillip, Thanks for the reply. Do u show some light on how to achieve:"If you only want to add a view to the existing display, put the view in ViewController's hierarchy and show/hide it." – Whoami Aug 06 '12 at 12:57
  • By that, I mean add the view as a subview inside `ViewController`'s .xib file and mark it hidden. Tapping the button sets the view's `hidden` property to NO. – Phillip Mills Aug 06 '12 at 13:31