对viewDidLoad的递归调用,崩溃

时间:2012-11-23 00:39:32

标签: ios xcode

loggerViewController.m中的

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView* mainView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:mainView]; // <-- Problem is here
}

loggingViewController是我的appDelegate的iVar

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    .
    .
    loggingViewController = [[loggerViewController alloc] init];
    [loggingViewController.view setBackgroundColor:[UIColor blueColor]];
//    [loggingViewController loadView];
    [self.view addSubview:loggingViewController.view];

}

我期待我的AppDelegate调用loggingViewController,而后者又在里面建立了自己的子视图,并且它将完成。但是,相反,viewDidLoad被递归调用,我不明白为什么?

1 个答案:

答案 0 :(得分:1)

尝试这样,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    loggingViewController = [[loggerViewController alloc] init];
    self.window.rootViewController = loggingViewController;
    [self.window makeKeyAndVisible];
}

递归调用的原因是您的self.viewnil,因此当您尝试将其添加为appdelegate视图的子视图时,它会尝试反复调用。

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView* mainView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:mainView];
}