views:

63

answers:

1

Why doesn't the following code work?

MyViewController *viewController = [[MyViewController alloc] init];
[myWindow addSubview:viewController.view];
[viewController release];

As I understand, myWindow should be retaining viewController.view for as long as the window needs it. So why does this cause my app to crash on launch? (commenting out the last line fixes the problem, as expected)

+9  A: 
[viewController release];

You are releasing viewController and not the view. myWindow will retain the view that you pass in, but not the view controller itself, which is causing it to be deallocated.

Since view is retained by the view controller when it is initialized and then retained by myWindow when you add it, I imagine the crash is because of subsequent calls to viewController (which will now be deallocated).

Perspx