为什么覆盖UITableViewController中的loadView修复了与多个视图控制器关联的tableView崩溃?

时间:2012-09-27 18:00:25

标签: ios uinavigationcontroller uitableview uiapplicationdelegate

当应用程序加载时出现以下错误,我有一个崩溃的应用程序(仅在iOS 6中):

Application windows are expected to have a root view controller at the end of application launch
*** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'A view can only be associated with at most one view controller at a time!
View <UITableView: 0xc21a800; frame = (0 20; 320 460); clipsToBounds = YES; opaque = NO; autoresize = W+H; gestureRecognizers = <NSArray: 0xbfb9d50>; layer = <CALayer: 0xbfb9720>; contentOffset: {0, 0}> is associated with <RootViewController: 0xbfbbb40>. Clear this association before associating this view with <RootViewController: 0xbfac010>.'

我的applicationDidFinishLaunchingWithOptions看起来像这样:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    // Add root nav controller below everything else
    RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStyleGrouped];
    rootViewController.title = @"My App";
    NSArray *sectionNames = [NSArray arrayWithObjects:@"Sec 1", @"Sec 2", @"Sec 3", nil];
    rootViewController.sectionNames = sectionNames;

    UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    self.navigationController = aNavigationController;

    if ([self.window respondsToSelector:@selector(setRootViewController:)]) {
        self.window.rootViewController = aNavigationController;
    } else {
        [self.window addSubview:aNavigationController.view];
    }

    // Add fake loading image
    NSString* imageName = @"Default-Portrait.png";
    theImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    theImageView.frame = CGRectMake(0,0,320,480);

    [self.window addSubview:theImageView];

    return YES;
}

RootViewController只是UITableViewController的一个子类,除此之外没什么好处的:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.delegate = self;
    self.tableView.allowsSelection = YES;
    self.userDefaults = [NSUserDefaults standardUserDefaults];
}

我有一个.xib文件,但我没有使用它进行初始化,无论该文件是否存在,都会出现此错误。

令人惊讶的是,当我将它添加到RootViewController时,错误消失了:

- (void)loadView {
    [super loadView];
}

这是解决问题的[超级loadView],我甚至不应该这样说。为什么?

0 个答案:

没有答案