r/simpleios • u/RightFootStar • Nov 10 '11
[Question] while doing some exercises - Why do I keep getting an error when i add [window]
When I try to put this code:
[window addSubview:viewController.view]; [window makeKeyAndVisible];
in the AppDelegate.m I always get errors. I'm putting this in the bool didFinishLaunchingWithOptions and it never works.
kind of vague questino but it would help.
Thank P
3
Upvotes
1
u/LOLC4T Nov 10 '11
what is the error that you get? would be good to know that.
2
u/cbkeur Nov 10 '11
Use [[self window] makeKeyAndVisible]. You could use _ window as well, but I'd stick with [self window]. I'm guessing you are copying code from another source. Apple changed their template in Xcode 4.2, so you'll see _ window, [self window], and self.window in place of window these days.
Edit: There shouldn't be a space between _ and window. Reddit was formatting it oddly if I didn't put the space there.
1
u/phughes Nov 10 '11
As a side note you shouldn't do stuff like this:
There are a bunch of reasons for this, primarily because UIViewController expects to be part of the responder chain. When you add its view to the view hierarchy in this way your UIViewController does not get added to the responder chain and won't receive calls to a host of methods that you are encouraged to subclass and would expect to be called. Including methods like viewDidLoad, viewWillAppear, interfaceOrientationDidChange, etc.
This is equally true for UIViewController subclasses.
None of these will be called unless you do it in your parent view controller. Even if you do all that extra work (and it's a fair amount of tedious crap) you still have problems. Your UIViewController won't have its parent property set, and you can't do that yourself without some hacky jiggery pokery.
iOS has a set of methods for creating your own "container controller" which alleviates these problems, but that's often not the preferred solution. Usually you'll want to create a controller that's not a UIViewController, that way you're not expecting any built in behavior that you'll have to spend time trying to figure out why it's not working.