objlv
objlv

Reputation: 601

NSTimer code is executing forever

Here is my code. I expected the timer to stop in 5 second after it starts but it doesn't. What is wrong here ?

-(void)loadView
{
NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];



NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.0
                                 target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:YES];
if([NSDate timeIntervalSinceReferenceDate] - startTime >= 5) {
    [timer invalidate];
}

}

-(void)targetMethod:(NSTimer *)timer {


    NSLog(@"bla");
}

Upvotes: 1

Views: 406

Answers (4)

mvds
mvds

Reputation: 47134

This is short and simple:

NSDate *endtime = [NSDate dateWithTimeIntervalSinceNow:5];
[NSTimer scheduledTimerWithTimeInterval:1
         target:self
         selector:@selector(timerTick:)
         userInfo:endtime
         repeats:YES];


-(void)timerTick:(NSTimer*)timer
{
    NSLog(@"timer tick");
    if ( [timer.userInfo timeIntervalSinceNow] < 0 )
    {
        [timer invalidate];
        NSLog(@"invalidating timer");
    }
}

Upvotes: 1

Simon Germain
Simon Germain

Reputation: 6844

NSDate's timeIntervalSinceReferenceDate is, by default, returning January 1st, 2001. Subtracting the same values will always be 0.

Apple's documentation: https://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

Here's an idea: In your .h

@interface MyClass : NSObject

@property (nonatomic, retain) NSTimer *timer;

- (void)targetMethod:(NSTimer *)timer;
- (void)cancelTimer;

@end

In your .m

@implementation MyClass

@synthesize timer;

-(void)loadView
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.0
                                             target:self
                                           selector:@selector(targetMethod:)
                                           userInfo:nil
                                            repeats:YES];
    [self performSelector:@selector(cancelTimer) withObject:nil afterDelay:5.0];
}

-(void)cancelTimer {
    [self.timer invalidate];
}

-(void)targetMethod:(NSTimer *)timer {
    NSLog(@"bla");
}

Upvotes: 2

Andos
Andos

Reputation: 312

You get the 'startTime' value and the value you compare it to are identical. Your calculation will always give 0. You must store the 'startTime' in your loadView method and then use it in the calculation.

Upvotes: 0

peterept
peterept

Reputation: 4427

Your time difference is always 0 so you never invalidate it!

Try setting startTime before you set the timer.

Upvotes: 0

Related Questions