2

我有一个类似 GameScreen.m 的文件(这是一段简化的代码):

- (IBAction) onCellClick:(id) sender
{
  points +=1;
  self.myScore.text = [[NSNumber numberWithInt: points] stringValue]; 
 //myScore is a label in GameScreenViewController xib
} 

也就是说,在单击视图中的单元格时,它会将文本标签增加 1。到目前为止一切顺利。

然后,在相同的代码中,我有一个计时器:

- (void) startTimer
{ 
    [NSTimer scheduledTimerWithTimeInterval:1.0f
                                     target:self
                                   selector:@selector(updateCounter:)
                                   userInfo:nil
                                    repeats:YES];
}

它的 updateCounter 方法是:

- (void) updateCounter:(NSTimer *)theTimer
{
     int seconds;
     static int count = 0;
     count +=1;
     timeElapsed = [[NSString alloc] initWithFormat:@"%d", seconds + count];
     self.time.text = timeElapsed;
     //time is a label in GameScreenViewController xib
}

问题是在这种情况下“时间”标签没有更新(每次 1 秒)。我插入了一个 AlertView 来检查 startTimer 方法是否有效并正确调用,它实际上是(它每秒显示一个恼人的 alertview 和 timeElapsed 值)。但是,我无法更改要更改的时间标签值。

为什么我的分数标签在操作时更新,而时间标签不是每秒更新一次?有什么方法可以在不将我的代码包含在 ViewController 中的情况下更新它?

//注意:我的代码分为三个文件:appDelegate 翻转屏幕并在它们之间发送值;我的 viewControllers 只是窗口,最后,我的 GameScreen 类管理所有进程。在 xib 中,File's Owner 连接到 ViewController,而视图连接到 GameScreen 类。

非常感谢您的任何反馈,请随时询问所需的任何附加代码。

4

2 回答 2

0

我经历了一次丑陋的绕行。它在某种程度上有效,但我经历了如此糟糕的修复,以至于我不好意思分享......

基本上,我将我的计时器直接移动到 ViewController,因为我希望它在视图加载时被触发,并且不能让它与从 ViewController 的 -(void)viewDidLoad 到 GameScreen 的 -(void) startTimer 的调用一起工作。涉及这两种方法的所有其他内容几乎都是重复的(好吧,不是重复的,假设是“多态”,因为我处理了一些变量来触发它们)。

看来我的 GameScreen.m IBActions 只能在我的 GameScreen.m 中触发其他方法,而不是在 GameScreenViewController.m 上。因此,我在 GameScreen.m 上处理按钮的行为,在 GameScreenViewController.m 上,我只处理“自动”的东西;也就是说,任何不依赖于用户交互的东西。它使我根据需要的输入/输出复制了一些 IBOutlets,所以我猜想,既然它现在正在工作,如果你不深入了解,你就无法区分...

不过感谢大家的反馈。

于 2011-11-24T09:32:38.947 回答
0

您必须在主线程中执行此操作(与 UI 相关的操作)。

而不是线,

 self.time.text = timeElapsed;

执行以下操作:

[self.time performSelectorOnMainThread:@selector(setText:) withObject:timeElapsed waitUntilDone:NO];

编辑:

- (void) updateCounter:(NSTimer *)theTimer
{
     //int seconds;
     static int count = 0;
     count +=1;
     NSString *timeElapsed1 = [[NSString alloc] initWithFormat:@"%d", count];
    [self.time performSelectorOnMainThread:@selector(setText:) withObject:timeElapsed1 waitUntilDone:NO];
    [timeElapsed1 release];
     //time is a label in GameScreenViewController xib
}
于 2011-11-22T12:29:00.077 回答