调用睡眠(5); 并更新文本字段不工作
我想睡一个方法(见下文),而不是从textLabel
的值改变的myTextLabelString
,等待5秒钟,更改为“睡眠5工作”,等待5秒,最后更改为“睡眠5第二次工作一轮“….它只是从myTextLabelString
的值,等待10秒,然后改变为”第二次睡觉5“。
- (void)textLabelChanger:(id)sender { NSString *myTextLabelString = [NSString stringWithFormat:@"%d", gameCountDown]; textLabel.text=myTextLabelString; sleep(5); textLabel.text=@"sleep 5 worked"; sleep(5); textLabel.text=@"sleep 5 worked second time round"; return; }
这可能会提供您寻求的结果:
-(void)textLabelChanger:(id)sender { NSString *myTextLabelString = [NSString stringWithFormat:@"%d", gameCountDown]; textLabel.text=myTextLabelString; [self performSelector:@selector(updateTextLabelWithString:) withObject:@"sleep 5 worked" afterDelay:5.0]; [self performSelector:@selector(updateTextLabelWithString:) withObject:@"sleep 5 worked second time round" afterDelay:10.0]; } -(void)updateTextLabelWithString:(NSString*)theString { textLabel.text=theString; }
有很多方法可以做到这一点。 您可以使用doFirstTextUpdate
来写入“sleep 5 worked”,然后在另一个5秒的延迟之后使用相同的[self performSelector:]
技术调用另一个select器,如doSecondTextUpdate
,而不是使用一个updateTextLabelWithString
。
Objective-C需要使用sleep()
方法,这是非常罕见的。
-(void)textLabelChanger:(id)sender { NSString *myTextLabelString = [NSString stringWithFormat:@"%d", gameCountDown]; textLabel.text=myTextLabelString; [self performSelector:@selector(firstUpdate) withObject:nil afterDelay:5.0]; } -(void)firstUpdate { textLabel.text = @"sleep 5 worked"; [self performSelector:@selector(secondUpdate) withObject:nil afterDelay:5.0]; } -(void)secondUpdate { textLabel.text = @"sleep 5 worked second time round"; }
UIKit组件的更改通常不会生效,直到您退出到runloop。 既然你从不故意阻塞主线程(而且,我假设你的代码只是一个睡眠testing,而不是你真正想要做的事情),这通常不是问题。
如果你真的想validation睡眠是否正常(所有的日志都有一个时间戳),可以尝试使用NSLog来设置'text'属性,使用performSelector:afterDelay:如果你希望在暂停之后在主线程上发生一些事情。
几乎所有的GUI编程工具包都是一个典型的问题。 如果您在事件处理线程中hibernate,则该线程被绑定,并且无法更新屏幕。 如果您需要进行定期更新屏幕的正在进行的工作,那么您必须在单独的线程中完成这项工作。 这就是你必须在这里做的。
正如已经提到的,阻塞主线程可能不是你想要做的。 而不是试图阻止你的应用程序做任何事情,包括重画屏幕或响应触摸,5秒钟从不同的angular度思考问题。 创build一个NSTimer来安排将来5秒的方法调用,并让您的应用程序继续运行,同时等待该定时器启动。