【问题标题】:iphone: performSelector: withObject: afterDelay: does not work with a background thread?iphone:performSelector:withObject:afterDelay:不能与后台线程一起使用?
【发布时间】:2010-08-31 23:11:24
【问题描述】:

我想在后台线程中运行一个方法,第一个方法将在几秒钟后在同一个(后台)线程上运行另一个方法。我是这样写的:

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

但是第二个方法永远不会被调用,为什么?还有,我怎样才能实现我的目标?

谢谢

【问题讨论】:

    标签: iphone objective-c iphone-sdk-3.0


    【解决方案1】:

    您必须有一个运行循环才能使 performSelector:withObject:afterDelay: 工作。


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

    添加:

    [[NSRunLoop currentRunLoop] run];
    

    first结尾。

    【讨论】:

    • 哎哟......不。那应该是问题所在。谢谢!
    • 我不明白,你怎么能没有运行循环?
    • 我也不明白。这个答案能具体一点吗?
    • 你有一个运行循环,因为它们带有线程,但没有任何东西自动导致运行循环运行。您需要附加输入(例如NSPort)或计时器才能实现。如果你想要一个刚刚运行的第二个运行循环,通常会孵化一个在其运行循环上反复调用runUntilDate: 的线程,直到出现退出条件。
    • 回答了我自己的问题:来自 NSRunLoop 文档:If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:. In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers. performselector:afterdelay: 在当前运行循环中添加了一个计时器。这需要在调用 run 之前完成
    猜你喜欢
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 2020-03-10
    • 1970-01-01
    相关资源
    最近更新 更多