我正在尝试休眠一个方法(见下文),但是textLabel不是从myTextLabelString的值更改,等待5秒,更改为“睡眠5工作”,等待5秒,最后更改为“睡眠5工作第二次循环”……它只是从myTextLabelString的值开始,等待10秒,然后更改为"sleep 5 worked second time Round.“。
- (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;
}发布于 2011-04-30 00:49:22
这可能会得到您想要的结果:
-(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;
}有很多方法可以做到这一点。你可以让一个updateTextLabelWithString写成“睡眠5工作”,然后在另一个5秒的延迟后使用相同的[self performSelector:]技术调用另一个选择器,而不是让一个doFirstTextUpdate调用两次不同的延迟。
需要在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";
}发布于 2011-04-29 23:37:07
对UIKit组件所做的更改通常不会生效,直到您退出运行循环。因为您从来不会故意阻塞主线程(而且,我假设您的代码只是一个睡眠测试,而不是您真正想做的事情),所以这通常不是问题。
如果您确实想验证睡眠是否正常(所有日志都有时间戳),请尝试使用NSLog代替设置'text‘属性,如果您希望在暂停后在主线程上发生某些事情,请使用performSelector:afterDelay:。
发布于 2011-04-29 23:34:19
这是几乎所有GUI编程工具包的一个典型问题。如果你在事件处理线程上休眠,那么这个线程就会被占用,并且它不能更新屏幕。如果您需要执行定期更新屏幕的持续工作,则必须在单独的线程中执行该工作;这就是您必须在此处完成的工作。
https://stackoverflow.com/questions/5834062
复制相似问题