NSTimer
lastmod 2014-02-14created 2014-02-142 edits
Sample code
A simple timer implementation example:
// + (NSTimer *) scheduledTImerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
// scheduledTimerWithTimeInterval : 몇초마다 실행시킬 것인지.
// target : 컨트롤 할 곳.
// selector : 무엇을 실행시킬 것인지.
// userInfo : 새로운 타이머의 정보전달자. (주의 : userInfo를 통해 변수를 넘길때 autorelease 된 정보를 넘기지 않도록 주의..)
// repeats : 반복할지 안할지 선택.
// 사용예제
// 1초마다 반복해서 countDown 함수를 호출한다.
// 전역변수 t_count 가 100이 되면 (즉, 타이머 실행후 100초 뒤) 타이머를 종료한다.
- (void)viewDidLoad
{
[super viewDidLoad];
t_count = 0;
my_timer_1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES]; // 1초마다 반복해서 countDown 함수를 호출한다.
}
- (void) countDown:(NSTimer *)aTimer {
t_count = t_count + 1;
if (t_count == 100) {
[my_timer_1 invalidate]; // 타이머 종료.
}
}
Troubleshooting
Solutions to problems related to NSTimer.
Message sent to deallocated instance
You may see an error message like the following.
When using ARC, it can be solved as follows.
waitingOpponentTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(waitingOpponentTimeOut)userInfo:nil repeats:NO] retain];
Alternatively, if it is not running on the Main Thread, it can be solved as follows.3
[self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:NO];
// ...
- (void) startTimer
{
_progressTimer = [[NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL_SECOND
target:self
selector:@selector(updateProgress:)
userInfo:nil
repeats:YES] retain];
}
- (void) updateProgress:(NSTimer*)timer
{
// ...
}
Pages that link here