Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - NSTimer not repeating after fire

Tags:

iphone

nstimer

I am creating and firing a NSTimer with:

ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                           target:self
                                         selector:@selector(handleTimer:)
                                         userInfo:nil
                                          repeats:YES];
[ncTimer fire];

AND

- (void)handleTimer:(NSTimer *)chkTimer {
    // do stuff
}

I am retaining my timer with:

@property (nonatomic, retain) NSTimer *ncTimer;

For some reason the timer is not repeating. It is firing once only and than never again.

like image 647
Zigglzworth Avatar asked Jan 23 '11 11:01

Zigglzworth


3 Answers

The -fire: method manually fires it once. For a timer to be started and repeat, you have to add it to a runloop using [[NSRunLoop currentRunLoop] addTimer: forMode:]

like image 60
Walter Avatar answered Nov 06 '22 11:11

Walter


Got it

Adding timer to mainRunLoop made it working 😆😆😆

Here you go:

Objective C:

self.ncTimer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

Swift 2

var ncTimer = NSTimer(timeInterval: 2.0, target: self, selector: Selector("handleTimer"), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(ncTimer, forMode: NSDefaultRunLoopMode)

Swift 3, 4, 5

var ncTimer = Timer(timeInterval: 2.0, target: self, selector: #selector(self.handleTimer), userInfo: nil, repeats: true)
RunLoop.main.add(ncTimer, forMode: RunLoop.Mode.default)
like image 29
Vaibhav Saran Avatar answered Nov 06 '22 13:11

Vaibhav Saran


You can't just assign to the timer that you have put as a property in your header. This should work:

self.ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self selector:@selector(handleTimer:) userInfo:nil repeats: YES];

Also: The fire method fires the timer, out of cycle. If the timer is non repeating it is invalidated. After the line that says fire, add this:


BOOL timerState = [ncTimer isValid];
NSLog(@"Timer Validity is: %@", timerState?@"YES":@"NO");
like image 8
Aurum Aquila Avatar answered Nov 06 '22 12:11

Aurum Aquila