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)
You are releasing
viewControllerand not the view.myWindowwill retain the view that you pass in, but not the view controller itself, which is causing it to be deallocated.Since
viewis retained by the view controller when it is initialized and then retained bymyWindowwhen you add it, I imagine the crash is because of subsequent calls toviewController(which will now be deallocated).