Question

How i can start an other viewcontroller in a thread?

My code don't work:

- (IBAction)btnGotoNextVC:(id)sender
{
    [self.isLoading startAnimating];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    [NSThread detachNewThreadSelector:@selector(gotoSecondController:)
                             toTarget:self
                           withObject:[NSArray arrayWithObjects:@"hello there", nil]];
}

and my thread:

- (void) gotoSecondController: (NSArray*) parameters
{
    NSString* data1 = parameters[0];

    NSLog(@"%@", parameters[0]);

    ViewController2 *VC2 = [self.storyboard instantiateViewControllerWithIdentifier:@"myView2"];
    VC2.global_myLabel = [NSString stringWithFormat:@"Hallo %@", data1];
    [self presentViewController:VC2 animated:YES completion:nil];
}

It's crashed by this line:

[self presentViewController:VC2 animated:YES completion:nil];

Error is:

-[NSStringDrawingContext animationDidStart:]: unrecognized selector sent to instance 0x8f983c0

What can i do? Thanks for answers!

Was it helpful?

Solution

No, anything that updates the UI has to be run on the main thread.

To fix your code, you will have to run in on the main thread. The easiest way would be to call the method directly, becasue IBActions are always invoked on the main thread:

[self gotoSecondController:@[@"hello there"]];

However, if you are not on the main thread already, you can make some code run on the main thread in a couple different ways. With blocks:

__block MyViewController *blockSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    [blockSelf gotoSecondController:@[@"hello there"]];
});

Or by using the method

[self performSelectorOnMainThread:@selector(gotoSecondController:) withObject:@[@"hello there"] waitUntilDone:NO];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top