2010-08-31 31 views
7

我想在后台线程中运行一个方法,第一个方法会在几秒钟后在同一个(后台)线程上运行另一个方法。我写这个:iphone:performSelector:withObject:afterDelay:不适用于后台线程?

- (IBAction)lauch:(id)sender 
{ 
    [self performSelectorInBackground:@selector(first) withObject:nil]; 

} 
-(void) second { 
    printf("second\n"); 
} 
-(void) first { 
    NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init]; 
    printf("first\n"); 

    [self performSelector:@selector(second) withObject:nil afterDelay:3]; 

    printf("ok\n"); 
    [apool release]; 
} 

但是第二种方法从来没有被调用过,为什么?而且,我怎样才能完成我的目标?

感谢

回答

9

你必须有performSelector运行的运行循环:withObject:afterDelay:上班。


你的代码执行first,当first退出,线程消失了。你需要运行一个运行循环。

地址:

[[NSRunLoop currentRunLoop] run]; 

first结束。

+0

ouch ... no。这应该是问题。谢谢! – subzero 2010-09-01 00:05:55

+2

我不明白,你怎么没有运行循环? – bogardon 2011-11-29 23:49:57

+0

我也不明白。这个答案可以更具体一点吗? – 2012-08-23 12:21:57