views:

79

answers:

1

Hi I am new to objective c. I am trying to make an app for iphone. I have a button on my view, and the click on which the function playSound is called. This is working properly. It does plays the sound that i want it to. Now the problem is with the timer. I want the timer to start on the click on the same button, and the timer value will be displayed in a label. I am not very clear with the NSTimer itself either yet. I guess i am doing something wrong here. Can anyone help me with this.

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

Using the code above, when i click on the button, it plays the sound, and then my app closes.

Thanks Zeeshan

+2  A: 

This line:

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

makes absolutely no sense. The timer will call the method you specify as the selector in scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: when it fires so you have to implement that method and update your label there. The first line of startTimer is almost correct, but the selector must include a colon (because it denotes a method that takes one parameter):

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

Note that I named the selector timerFired: so we have to implement that method. If you want the timer to increment a counter, you will have to do that in this method, too:

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

Don't forget to invalidate the timer later when you no longer need it.

Ole Begemann
THanks ole Begemann
Zeeshan Rang