Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 306
Pierre Avatar asked Jan 23 '26 10:01

Pierre


1 Answers

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;
}
like image 197
Joe Avatar answered Jan 25 '26 11:01

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!