1

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!

1 Answers1

1

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];
cjwirth
  • 2,015
  • 1
  • 15
  • 24
  • Thank you for your answer! But I have an UITableView and i get the source code from a webpage and parse it. Now, the UI stucks when i call the function for reading the source code from page. How can i fix this? The First Controller stucks when I click on the button and read the website code.. Yet, thanks for your quick answer. – user3032152 Nov 25 '13 at 12:22
  • I guess that depends on what makes it suck... Are you loading or parsing all of the HTML on the main thread? That would tie things up. You can create and pass data to a UIViewController on a separate thread, and then present it on the main thread, would that work for you? Note that Im not sure if you can change label text on separate threads, so you would have to process that in the background thread, andvthen update the label on the main thread – cjwirth Nov 25 '13 at 12:40