我想在viewdidload上启动NSTimer,然后以特定的时间间隔执行一些void函数。我该怎么做?
谢谢!
答案 0 :(得分:2)
这是你的基本模式:
MyViewController.h:
...
@interface MyViewController : UIViewController
{
...
NSTimer* timer;
...
}
...
MyViewController.m:
...
static const NSTimeInterval TIMER_INTERVAL = 1.0;
...
- (void)dealloc
{
[self stopTimer];
...
[super dealloc];
}
...
- (void)viewDidLoad
{
...
[self startTimer];
...
}
...
- (void)startTimer
{
[self stopTimer];
timer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL
target:self
selector:@selector(timerCallback)
userInfo:nil
repeats:YES];
[timer retain];
}
...
- (void)stopTimer
{
if (timer)
{
[timer invalidate];
[timer release];
timer = nil;
}
}
...
- (void)timerCallback
{
someFunction();
[self someMethod];
}