Flappy
Flappy

Reputation: 867

Objective-c iPhone NSTimer unique identifier

I've got a question about a NSTimer that i declared in the .h file and later set inside a method. But this method will be called more then ones, so the NSTimer runs multiple times under the same name.

Now my question is, is it possible to set a tag/id or whatever so i can invalidate the NSTimer with the correct tag/id?

Thanks for help!

Upvotes: 3

Views: 1032

Answers (4)

lucasart
lucasart

Reputation: 1685

This question was asked long ago, but since I had the same need today, here's my solution:

// set timer
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(whateverMethod)
                                       userInfo:@"timer1"
                                        repeats:YES];

To invalidate this same timer, check its userInfo string:

// invalidate timer
if ([[timer userInfo] isEqual:@"timer1"])
    [timer invalidate];

Upvotes: 4

Flappy
Flappy

Reputation: 867

Oke, i have now the following code. But is there nog way to set a unique ID/Tag so i can invalidate the timer on a later moment. This because the timer method will call more then ones. (its for animated images/buttons)

MainViewController.m

- (void)timerMethod {

     NSTimer *daTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(animations:) userInfo:nil repeats:YES];

}

Upvotes: 1

Ben Zotto
Ben Zotto

Reputation: 71048

If you're creating multiple NSTimers, and you care to handle them independently, you need to store them independently. If there are a fixed number, just create enough variables and name them appropriately. Or keep them in an array (which is then keyed by index). Or put them in a dictionary, keyed by some string name.

Your phrasing above ("runs under the same name") concerns me somewhat. Timers have some sensitive memory handling requirements. Edit your question with more details on what you're doing if you want broader design help.

Upvotes: 2

Brad
Brad

Reputation: 11515

You just have to save a reference to the NSTimer that you have created, and is running - and just use this reference.

Upvotes: 1

Related Questions