【发布时间】:2014-07-15 08:51:20
【问题描述】:
我正在寻找一种在我的应用程序空闲时以NSTextField 的间隔显示字符串的方法。我知道使用sleep 的一种方法,尽管我认为这不是处理这个问题的最佳方法。我在想NSTimerscheduledTimerWithTimeInterval 可能是一个不错的方法,但我不知道该怎么做。
这是我的代码:
- (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"]];
}
【问题讨论】:
-
问题中显示的代码不会显示任何内容,但您说它显示“标题”。你的实际代码是什么? (编辑您的问题,不要将其作为评论发布。)
-
@CRD,这是实际代码,here's the XCode project。当您运行项目时,它会显示“标题”。
-
在上面的代码中,
textLabel是一个未初始化的局部变量showTextAtInterval- 该代码不起作用。在您的实际代码中,textLabel是该类的IBOutlet实例变量。像这样的细节问题。我将在下面添加一个答案。 -
不是玩魔鬼的拥护者,但是即使您将实例变量更改为
NSTextView *textLabel而没有IBOutlet它仍然会做同样的事情。 -
关键是您的代码正在调用未初始化变量的方法,任何试图帮助您的人都会看到并指出问题所在。只是因为你写了它产生了输出,我才知道那不是你的代码。当您缩写代码以适应问题时,您必须小心不要引入错误或遗漏关键内容。 HTH
标签: objective-c cocoa nstimer nstextfield