Search code examples
objective-ciosuiapplicationdelegateaddsubviewretaincount

window addSubview release problem


I was wondering something about the app delegate of my app. Why can't I release like this :

-(BOOL)application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    RootViewController *controller = [[RootViewController alloc]
                                      initWithNibName:@"RootViewController"
                                               bundle:[NSBundle mainBundle]];
    [self.window addSubview:controller.view];
    [controller release]; // Here's my question
    [self.window makeKeyAndVisible];
    return YES;
}

I was almost sure that -addSubview method increase by 1 my retain count. So why do I have crash when I release my controller ? Why is it working in another class but the delegate ?

Thanks !


Solution

  • The other answers are correct, the UIVIewController is not being retained, what I recommend is setting the UIWindows rootViewController (only available iOS 4.0 and later) property which does retain the controller. If your app supports pre iOS 4.0 then you will need to store controller in an instance variable.

    -(BOOL)application:(UIApplication *)application
      didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        RootViewController *controller = [[RootViewController alloc]
                                          initWithNibName:@"RootViewController"
                                                   bundle:[NSBundle mainBundle]];
        //controller will be retained and view will set for you
        window.rootViewController = controller;
        [controller release];
        [self.window makeKeyAndVisible];
        return YES;
    }