Skip to content

NSTimer

Sample code

간단한 타이머 구현 예제는 아래와 같다.

// + (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

NSTimer와 관련된 문제점 해결방법을 정리한다.

Message sent to deallocated instance

아래와 같은 오류 메세지를 확인할 경우가 있다.

-[CFRunLoopTimer invalidate]: message sent to deallocated instance 0x109b05a0

ARC를 사용할 경우 아래와 같이 해결할 수 있다.

waitingOpponentTimer = [[NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(waitingOpponentTimeOut)userInfo:nil repeats:NO] retain];

또는 Main Thread에서 실행하지 않을 경우 아래와 같이 해결할 수 있다.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
{
    // ...
}