叫睡(5);并更新文本字段不起作用

时间:2011-04-29 15:31:26

标签: objective-c cocoa-touch ios sleep

我正在尝试睡一个方法(见下文),而不是textLabelmyTextLabelString的值改变,等待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;
}

4 个答案:

答案 0 :(得分:11)

这可能会提供您寻求的结果:

-(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写入“sleep 5 working”,然后使用相同的{doFirstTextUpdate来调用doSecondTextUpdate之类的[self performSelector:],而不是让您使用不同的延迟调用两次sleep()。 {1}}技术再延迟5秒。

您需要在Objective-C中使用-(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"; } 方法,这是非常罕见的。

{{1}}

答案 1 :(得分:3)

在您退回runloop之前,对UIKit组件的更改通常不会生效。因为你从不故意阻止主线程(并且,我认为,你的代码只是一个睡眠测试,而不是你真正想做的事情),这通常不是问题。

如果您确实要验证睡眠是否正常(所有日志都有时间戳),请尝试使用NSLog代替设置'text'属性,使用performSelector:afterDelay:如果您想在暂停后在主线程上发生某些事情

答案 2 :(得分:2)

这是几乎所有GUI编程工具包的经典问题。如果你在事件处理线程上睡觉,那么该线程就会被绑定,并且它无法更新屏幕。如果您需要定期更新屏幕的正在进行的工作,那么您必须在单独的线程中完成该工作;这就是你必须在这里做的事情。

答案 3 :(得分:2)

如前所述,阻止主线程可能不是你想要做的。而不是试图阻止你的应用程序做任何事情,包括重绘屏幕或响应触摸,5秒钟从不同的角度思考问题。创建NSTimer以在将来5秒内安排方法调用,并在等待该计时器触发时让您的应用程序继续运行。

相关问题