为什么这个发布的视图控制器在发出消息时不会导致崩溃

Sup*_*hin 0 iphone memory-management objective-c

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create the navigation and view controllers
    RootViewController *rootViewController = [[RootViewController alloc]
                                              initWithStyle:UITableViewStylePlain];
    UINavigationController *aNavigationController = [[UINavigationController alloc]
                                             initWithRootViewController:rootViewController];
    self.navigationController = aNavigationController;
    [aNavigationController release];
    [rootViewController release];

    [rootViewController setRegions:[Region knownRegions]];

    // Configure and display the window
    [window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}
Run Code Online (Sandbox Code Playgroud)

这里,在上面的代码中,引用'rootViewController'用于发送消息'setRegions:',即使在上一行中释放了对象之后也是如此.

如果它是错的那么模拟器如何运行而没有任何崩溃?或者如果它是正确的,又如何?,我看不出自动释放和释放之间的区别.

消息来源: - http://developer.apple.com/iphone/library/samplecode/TableViewSuite/listing12.html

下载: - developer.apple.com/iphone/library/samplecode/TableViewSuite/index.html

Bra*_*nar 5

rootViewController保留的对象被保留,aNavigationController因此其保留计数为2,并aNavigationController在分配时保留,self.navigationController因此其保留计数为2.因此,当您释放rootViewController并且aNavigationController它们的保留计数降至1时,所以它们不会被收集,所以你仍然可以通过他们的参考访问它们.

编辑

只有在保留计数达到0时才会收集对象,并且对对象的任何引用仍然有效(即使引用已被释放),直到此时为止.通常情况下,您不希望依赖于此并且应该在释放对象之前进行调用,但在这种情况下它确实有效.