NSTimer not calling Method

sinθ picture sinθ · Mar 20, 2013 · Viewed 7.5k times · Source

I have an NSTimer that should call a method every second, but it doesn't seem to be calling it at all.

This is how I declare the timer:

[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fadeManager:) userInfo:nil repeats:YES];

This is the method it calls:

-(void) fadeManager: (NSTimer*) timer{
    NSLog(@"IT'S WORKING!");
    self.playHead += .1; // keeps track of where they are in full track
    if (self.playHead >= self.wait  && ![player isPlaying]) { // checks if wait is over
        [player play];
    }
    if (self.playHead >= self.duration + self.startTime && [player isPlaying]) { // checks if full duration is over
        [player pause];
        [self reset];
    }
    int fadeOutArea = self.startTime + self.duration - self.fadeOut;
    int fadeInArea = self.startTime + self.fadeIn;
    if (self.playHead <= fadeInArea && [player volume] < relativeVolume) { // checks if fadingIn.
        [self fadeInIncriment];
    }
    if (self.playHead >= fadeOutArea  && [player volume] > 0) {
        [self fadeOutIncriment];
    }
}

The code was not working so I put the NSLog in as well as a break point. It seems that it is never being called. Why is this? Does it matter that I declared the method in the .m file like this:

#import <AVFoundation/AVFoundation.h>
@interface CueMusic ()

- (void) delayFadeOut: (AVAudioPlayer*) dFade;
- (void) fadeInIncriment;
- (void) fadeOutIncriment;
- (void) fadeManager: (NSTimer*) timer; // <--------
- (void) start;

@end

@implementation CueMusic
 .......

Answer

Inder Kumar Rathore picture Inder Kumar Rathore · Mar 20, 2013

Either use

NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fadeManager:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

or

//schedules the timer
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(fadeManager:) userInfo:nil repeats:YES];

From the docs Scheduling Timers in Run Loops


Swift Code

Either

let timer: NSTimer = NSTimer(timeInterval: 1.0, target: self, selector: "fadeManager:", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)

Or

//schedules the timer
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "fadeManager:", userInfo: nil, repeats: true)