1

I am having trouble with NSTimer. The below code is called from a method and it creates an NSTimer and sets it to the instance variable self.syncDelay. The if statement at the end of the method checking if the timer is valid gets called.

However when I call this method again before the timer runs out, the if statement at the top of the method doesn't get called. Which, I am guessing, is why [self.syncDelay invalidate]; doesn't invalidate the timer.

I have a property defined as: @property (nonatomic, strong) NSTimer *syncDelay;

The functionality I am looking for is the timer being invalidated when the method is called for the second time before the timer runs out and creating a new timer. Thus effectively resetting the timer.

EDIT: When the method gets called for the second the NSTimer is nil. Which is strange as I am keeping a strong pointer to it.

else {
    if ([self.syncDelay isValid]) {
        NSLog(@"Timer valid at start of method");
    }

    [self.syncDelay invalidate];

    self.syncDelay = nil;

    NSInvocation *timerInvocation = [NSInvocation invocationWithMethodSignature:
                    [self methodSignatureForSelector:@selector(testMethod:)]];
    // configure invocation
    [timerInvocation setSelector:@selector(testMethod:)];

    [timerInvocation setTarget:self];

    [timerInvocation setArgument:&className atIndex:2];   // argument indexing is offset by 2 hidden args

    self.syncDelay = [NSTimer scheduledTimerWithTimeInterval:10
                                            invocation:timerInvocation
                                            repeats:NO];

    if ([self.syncDelay isValid]) {
        NSLog(@"Timer valid at end of method");
    }
}
pls
  • 1,522
  • 2
  • 21
  • 41
  • Where else is the timer used? Have you checked the method is called when you expect (the second log is printed?)? – Wain Nov 19 '13 at 10:12
  • The timer isn't used anywhere else. Yes the method is called correctly. – pls Nov 19 '13 at 10:15
  • 1
    Are you sure you are calling the method on the same object? – Sulthan Nov 19 '13 at 11:02
  • Sulthan thank you, thank you, thank you :-). I checked self and the pointer was different each time. If you put it as an answer I will mark it correct. Thanks again. – pls Nov 19 '13 at 13:58

0 Answers0