繁体   English   中英

Iphone NSTimer问题

[英]Iphone NSTimer Issue

嗨,我是目标c的新手。 我正在尝试为iPhone开发一个应用程序。 我的视图上有一个按钮,并单击了调用playSound函数。 这工作正常。 它确实播放了我想要的声音。 现在问题出在计时器上。 我希望计时器在单击同一按钮时启动,并且计时器值将显示在标签中。 我还是不太清楚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

这行:

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];
}

当您不再需要计时器时,别忘了使其失效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM