Autorelease scope

前端 未结 4 1251
野趣味
野趣味 2021-01-12 20:32

I was wondering how the autorelese works on the iPhone. I though that once you send an autorelease to an object it is guaranteed to be retained in till the

4条回答
  •  北海茫月
    2021-01-12 21:09

    To expand on Don's answer, it may be somewhat confusing to say "you give ownership of the object to the current autorelease pool." This might be misunderstood to mean the object is guaranteed to be destroyed when the autorelease pool is drained. This is not correct (though it will happen in this case). Sending -autorelease requests that the autorelease pool send a -release message when it is drained. If that -release message makes retainCount = 0, then the object will be destroyed.

    So, in order to do what Don is recommending, you need to create a ivar to keep track of this view controller. His explanation of why the view vanishes is exactly right; but you don't want to just leak the view controller. You want to hold onto it, and release it when you're done with it.

    @interface ... {
       LoginViewController *_loginViewController;
    }
    
    @property (readwrite, retain) LoginViewController *loginViewController;
    
    @implementation ...
    @synthesize loginViewController = _loginViewController;
    
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    
        self.loginViewController = [[[LoginViewController alloc] initWithNibName:@"LoginView" bundle:nil] autorelease];
    
        [window addSubview: [loginViewController view]];
        [window makeKeyAndVisible];
    }
    
    - (void)dealloc {
        [_loginViewController release]; _loginViewController = nil;
        [super dealloc];
    }
    

提交回复
热议问题