NSThread presentviewcontroller电话?

时间:2013-11-25 11:49:20

标签: nsthread

如何在线程中启动其他viewcontroller?

我的代码不起作用:

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

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

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

和我的主题:

- (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];
}

这条线坠毁了:

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

错误是:

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

我该怎么办?谢谢你的回答!

1 个答案:

答案 0 :(得分:1)

不,更新UI的任何内容都必须在主线程上运行。

要修复代码,您必须在主线程上运行。最简单的方法是直接调用方法,因为IBActions总是在主线程上调用:

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

但是,如果您已经不在主线程上,则可以通过几种不同的方式在主线程上运行一些代码。使用块:

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

或者使用方法

[self performSelectorOnMainThread:@selector(gotoSecondController:) withObject:@[@"hello there"] waitUntilDone:NO];