Search code examples
xcodeuisplitviewcontrollernstimerdelaydetailview

Use NSTimer to delay a subview display but failed


In a detail view in UISplitView, I want to add a subview to its UINavigationController's child view.

I use an NSTimer *delayTimer to delay the loading of child view because I fade in the detail view using animation.

delayTimer = [NSTimer scheduledTimerWithTimeInterval:1.3 target:self 
selector:@selector(loadWelcomeView) userInfo:nil repeats:NO];

The view I want to add is called welcomeview

- (void) loadWelcomeView 
{
    NSLog(@"Welcome View Loaded.");
    welcomeViewController = [[WelcomeView alloc] 
                         initWithNibName:@"WelcomeView" bundle:nil];
    [self.navigationController addChildViewController:welcomeViewController];
}

But when I ran the program and waited, it was totally blank!!!

However the message Welcome view loaded. WAS displayed in the debug window.

If I use [self loadWelcomeView]; instead of using an NSTimer, the welcomeview will be displayed PERFECTLY.

What procedure did I do wrong...?


Solution

  • UI stuff needs to happen on the main thread, so let's rule out any possible threading issues that might come in with NSTimers. Try doing this:

    - (void) loadWelcomeViewWithinMainThread
    {
        NSLog(@"Welcome View Loaded.");
        welcomeViewController = [[WelcomeView alloc] initWithNibName:@"WelcomeView" bundle:nil];
        if(welcomeViewController)
        {
            if(self.navigationController)
            {
                [self.navigationController addChildViewController:welcomeViewController];
            } else {
                NSLog( @"navigationController is null");
            }
        } else {
            NSLog(@"welcomeViewController is null");
        }
    }
    
    - (void) loadWelcomeViewWithinMainThread {
        [self performSelectorOnMainThread: @selector(loadWelcomeViewWithinMainThread) withObject: nil waitUntilDone: YES];
    }