esreli
esreli

Reputation: 5051

NSTimer not operating as expected

I hope this to be a simple fix, you tell me.

What I have is a class IVAR *timer of type NSTimer. When an IBAction is performed, a method is called that contains this code:

if (timer) timer = nil;
timer = [NSTimer timerWithTimeInterval:0.2 target:self selector:@selector(removeOverlay) userInfo:nil repeats:NO];

In the same class, I have a method:

- (void)removeOverlay {
...
}

That isn't fired after the time interval of .2 seconds.

Might you know what the problem is here?

Upvotes: 0

Views: 137

Answers (4)

Ahmed Al Hafoudh
Ahmed Al Hafoudh

Reputation: 8429

  1. Make sure the timer the instance of NSTimer is not released meanwhile.
  2. removeOverlay looks like it updates some UI. Make shure you call it on main thread.
  3. Put a breakpoint in the removeLayout method to see if it fires.
  4. You are not scheduling the timer. Replace the timerWithTimeInterval with scheduledTimerWithTimeInterval

To perform code on main thread (allows UI updating):

- (void)removeOverlay {
  dispatch_async(dispatch_get_main_queue(), ^{
     // update ui
  });
}

More on Grand Central Dispatch (GCD)

Upvotes: 2

pcs289
pcs289

Reputation: 129

If it only gets called once I'd use [self performSelector:@selector(removeOverlay) afterDelay:(seconds you want to delay the use the method removeOverlay)];

Upvotes: 0

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

Since no one mentioned it, an alternative to adding the timer to a run loop is to use the fire method:

[timer fire];

Upvotes: 1

Miles Alden
Miles Alden

Reputation: 1540

You need

 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

The timers work by placing the calls at the appropriate points in the run loop.

Upvotes: 1

Related Questions