开发者

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:@"Root开发者_开发百科ViewController"
                                               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 !


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;
}


This line

[self.window addSubview:controller.view];

increases the retain count of controller.view not controller. That's why

[controller release];

creates a problem.

If this is the main window, then you don't need to worry about the memory leak, because the window is active for the entire life of the program, and all memory is purged when it terminates.


addSubView increases the retain count of the view inside of the view controller, that is why the app crashes if you release the controller.

in any case, if you don't release it, you will have a leak. the solution is creating an ivar in your class and assigning to it the view controller (instead of a local variable), then release it in dealloc.


When you add view as subview then view gets retained, not its controller. So when you release controller it gets deallocated and its view - not. As result later view try to send messages to its already deallocated controller and app crashes.


This because you are the unique owner of that controller. You just add its view as a subview of the window. Although the view gets retained by the window's view, the controller not.

So, it will get deallocated and any further use of it will make your app crash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜