开发者

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 i开发者_运维知识库nvalidate the NSTimer with the correct tag/id?

Thanks for help!


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];


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.


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


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];

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜