Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 如何让主线程等待几秒钟,然后调用一个方法?_Objective C_C - Fatal编程技术网

Objective c 如何让主线程等待几秒钟,然后调用一个方法?

Objective c 如何让主线程等待几秒钟,然后调用一个方法?,objective-c,c,Objective C,C,我对Objective C编程非常陌生,我开始编写一个简单的练习。 我希望我的main()从类调用一个方法,并从该方法使用performSelector:(SEL)with object:afterDelay。 问题是它不调用方法,也不延迟。 //主要 //州立大学 -(void)complete{ NSLog(@"The door is Open (OPENING ==> OPEN)"); [door setState:[door openState]]; } -(vo

我对Objective C编程非常陌生,我开始编写一个简单的练习。 我希望我的
main()
从类调用一个方法,并从该方法使用performSelector:(SEL)with object:afterDelay。 问题是它不调用方法,也不延迟。 //主要

//州立大学

-(void)complete{
    NSLog(@"The door is Open (OPENING ==> OPEN)");
    [door setState:[door openState]];
}

-(void)startTimer{
    NSLog(@"The timer has started on Opening state");
//    timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(complete) userInfo:nil repeats:NO];
//    [timer retain];
//    [timer fire];
//    [timer release];
    [self performSelector: @selector(complete) withObject:nil afterDelay:30];
}
我对代码做了一点修改,但还是一样的。这不是代码其余部分的问题,而是
startTimer()
方法的问题,因为它不调用
complete()
方法。如果我使用NSThread(被注释掉),它将调用它,但仍然没有延迟。我环顾了所有的地方,我发现对于我来说这是最好的解决方案,但对我来说不起作用。 为了了解它对程序的作用,状态必须在“打开”时保持30秒,然后
完成
并将其设置为打开状态

要求您使用。在普通应用程序中,运行循环是设置并自动运行的。在命令行程序(如您的)中,您需要自己设置并运行run循环。示例代码


但是,如果您只想将程序延迟一点,而不需要执行任何其他操作,那么只需使用该函数就更简单。

将在当前运行循环上下文(调用插入运行循环上下文)上调用performSelector。如果在必须进行调用时,运行循环上下文不再处于活动状态,那么事情将不起作用

确保调用线程的调用运行循环处于活动状态。---如果您从主函数中显示更多代码,我可能会理解得更好


为什么线程解决方案对您有效——当您创建线程时,它将由进程执行——因此,不管调用运行循环,都会在进程范围内调用次线程。

@Adrian:运行循环是为您创建的,但您需要自己运行。谢谢您的回答,但我仍然没有完全理解。当我运行整个程序时,运行循环不是从我的主程序开始的吗?我的演讲者不是:。。。使用那个循环?再次感谢你!不,除非你运行它,否则它不会启动。请阅读我提供的关于运行循环的苹果文档的链接。运行循环并不难,您基本上需要在nsrunlop上调用正确的函数。@Girish:他没有阻塞事件循环,他没有事件循环。@JeremyP您是对的。。。我确信应用程序将被终止。。。在这种情况下,他最好毫不拖延地使用performSelector。[state startTimer];--这一行语句后面的代码是什么…在main()中,这是最后一行…然后进程将在需要的事情发生之前终止…但是当它到达我的startTimer()方法时,运行循环上下文不是处于活动状态吗?那么,为什么不等待几秒钟,然后调用它必须调用的方法呢?非常感谢您的帮助。run loop必须处于活动状态。当runloop必须调用“complete”函数时,您已经注册了调用。
-(void)complete{
    NSLog(@"The door is Open (OPENING ==> OPEN)");
    [door setState:[door openState]];
}

-(void)startTimer{
    NSLog(@"The timer has started on Opening state");
//    timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(complete) userInfo:nil repeats:NO];
//    [timer retain];
//    [timer fire];
//    [timer release];
    [self performSelector: @selector(complete) withObject:nil afterDelay:30];
}