我正在寻找一种在应用程序空闲时在NSTextField中间隔显示字符串的方法。我知道用sleep做这件事的一种方法,尽管我不认为这是最好的处理方法。我认为NSTimer scheduledTimerWithTimeInterval可能是一个很好的方法,但我不知道如何去做。
这是我的密码:
- (void)showTextAtInterval {
NSTextField *textLabel;
[textLabel setStringValue:[NSString stringWithFormat:@"06/01/14"]];
sleep(5);
[textLabel setStringValue:[NSString stringWithFormat:@"Headlines"]];
....
}编辑:尝试过,但只静态显示了“标题”。
[self startTimer];
- (void)startTimer {
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(showTextAtInterval) userInfo:nil repeats:YES];
return;
}
- (void)showTextAtInterval {
NSTextField *textLabel;
[textLabel setStringValue:[NSString stringWithFormat:@"06/01/14"]];
[textLabel setStringValue:[NSString stringWithFormat:@"Headlines"]];
}发布于 2014-05-26 14:40:27
初始化您的计时器
-(void)awakeFromNib{
[super awakeFromNib];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(showTextAtInterval) userInfo:nil repeats:YES];
}使用你的选择器:
- (void)showTextAtInterval {
NSTextField *textLabel;
[textLabel setStringValue:[NSString stringWithFormat:@"06/01/14"]];
[textLabel setStringValue:[NSString stringWithFormat:@"Headlines"]];
....
}发布于 2014-05-26 20:49:01
您的代码有正确的想法,只是需要一些更改。
首先,正如您发现的,不要使用sleep -这将完全停止当前线程,如果您从主线程调用它,就像您所做的那样,本质上就是您的应用程序。
有许多方法可以做到这一点。您选择的NSTimer是一个很好的选择,因为您说您只想在程序空闲时显示消息,NSTimer有一个invalidate消息,您可以使用它来停止定时器,当您的代码不再空闲时,您可以调用它。
UI更新必须发生在主线程上,不一定是同步的--从更新UI的方法返回,UI可能还没有反映更改。这就是为什么您只看到“标题”,在另一个之后有两个UI更新调用,第二个是在您看到第一个的效果之前完成的。
您需要做的是:暂停,显示第一条消息,暂停,显示第二条消息,在需要时重复。因此,更改代码,以便在第一个定时器触发器上显示第一条消息,第二次触发显示第二条消息,等等。您可以使用一个实例变量来跟踪应该首先显示哪条消息。最好创建一个带有方法的“空闲消息”类,以启动和停止消息,并将所有消息选择和显示逻辑保留在该类中,您的计时器和其他状态应该是该类的实例变量。确保所有UI更新都发生在主线程上,您可以通过确保在该线程上调度NSTimer来做到这一点(并将逻辑放在start方法中)。
HTH
发布于 2014-05-26 14:53:52
为了纠正错误,我认为您应该在showTextAtInterval中添加一个私有变量并进行一个切换。
- (void)showTextAtInterval {
NSTextField *textLabel;
switch(iTimer)
{
case 0:
[textLabel setStringValue:[NSString stringWithFormat:@"06/01/14"]];
break;
case 1:
[textLabel setStringValue:[NSString stringWithFormat:@"Headlines"]];
break;
....
}
iTimer ++;
}https://stackoverflow.com/questions/23872524
复制相似问题