iphonenstimer问题
嗨,我是c目标的新手。我正在尝试为iphone制作一个应用程序。我的视图上有一个按钮,单击该按钮调用函数playSound。这是正常工作。它确实播放我想要的声音。 现在问题出在计时器上。我希望计时器在单击同一按钮时启动,计时器值将显示在标签中。我对NSTimer本身也不是很清楚。我想我在这里做错了什么。有人能帮我吗iphonenstimer问题,iphone,objective-c,xcode,Iphone,Objective C,Xcode,嗨,我是c目标的新手。我正在尝试为iphone制作一个应用程序。我的视图上有一个按钮,单击该按钮调用函数playSound。这是正常工作。它确实播放我想要的声音。 现在问题出在计时器上。我希望计时器在单击同一按钮时启动,计时器值将显示在标签中。我对NSTimer本身也不是很清楚。我想我在这里做错了什么。有人能帮我吗 -(IBAction)playSound { //:(int)reps NSString *path = [[NSBundle mainBundle] pathForRes
-(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];
}
使用上面的代码,当我点击按钮时,它会播放声音,然后我的应用程序关闭
谢谢
泽山这一行:
labelA.text = [NSString stringWithFormat:@"%d", timer];
毫无意义。计时器将调用您在scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
中指定为选择器的方法,因此您必须实现该方法并在其中更新标签。startTimer
的第一行几乎是正确的,但选择器必须包含冒号(因为它表示采用一个参数的方法):
注意,我将选择器命名为timerFired:
,因此我们必须实现该方法。如果您想让计时器增加计数器,也必须使用此方法:
- (void)timerFired:(NSTimer *)timer {
static int timerCounter = 0;
timerCounter++;
labelA.text = [NSString stringWithFormat:@"%d", timerCounter];
}
当你不再需要计时器时,别忘了让它失效
- (void)timerFired:(NSTimer *)timer {
static int timerCounter = 0;
timerCounter++;
labelA.text = [NSString stringWithFormat:@"%d", timerCounter];
}