2009-11-14 56 views
0

嗨,我是新的目标C。我正在尝试为iPhone制作应用程序。我的视图上有一个按钮,并且点击了playSound函数。这工作正常。它确实播放我想要的声音。 现在的问题是与计时器。我希望计时器在点击同一个按钮时开始,计时器值将显示在标签中。我还不清楚NSTimer本身。我想我在这里做错了事。谁能帮我这个。Iphone NSTimer问题

-(IBAction)playSound { //:(int)reps 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"chicken" ofType:@"wav"]; 
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path]; 
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
    theAudio.delegate = self; 
    [theAudio play]; 

    [self startTimer]; 
} 

- (void)startTimer { 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(targetMethod) userInfo:nil repeats:YES]; 
    labelA.text = [NSString stringWithFormat:@"%d", timer]; 
} 

使用上面的代码,当我点击按钮,它播放声音,然后我的应用程序关闭。

感谢 Zeeshan

回答

2

这条线:

labelA.text = [NSString stringWithFormat:@"%d", timer]; 

使得完全没有意义的。计时器会在触发时调用您在scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:中指定的方法作为选择器,因此您必须实施该方法并在那里更新您的标签。的startTimer第一行几乎是正确的,但选择必须包括冒号(因为它表示一个参数的方法):

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

注意,我命名为选择timerFired:所以我们必须实现该方法。如果您希望定时器递增计数器,你将不得不做,在这种方法中,也:

- (void)timerFired:(NSTimer *)timer { 
    static int timerCounter = 0; 
    timerCounter++; 
    labelA.text = [NSString stringWithFormat:@"%d", timerCounter]; 
} 

不要忘了计时器后无效,当你不再需要它。

+0

感谢OLE Begemann – 2009-11-14 04:33:18