1) scheduled timer & using selector NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector:@selector(onTick:) userInfo: nil repeats:NO]; 한번만 호출 할 경우 타이머 대신 사용 가능한 간단한 코드 [self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0]; 2) self-scheduled timer NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0]; NSTimer *t = [[NSTimer alloc] initWithFireDate: d interval: 1 target: self selector:@selector(onTick:) userInfo:nil repeats:YES]; NSRunLoop *runner = [NSRunLoop currentRunLoop]; [runner addTimer:t forMode: NSDefaultRunLoopMode]; [t release]; 특정한 시간(여기선 1분)후에 자동으로 작동하는 타이머 (반복:YES일 경우 1분마다 콜) 3) unscheduled timer & using invocation NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)]; NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn]; [inv setTarget: self]; [inv setSelector:@selector(onTick:)]; NSTimer *t = [NSTimer timerWithTimeInterval: 1.0 invocation:inv repeats:YES]; 위의 코드까지 쓴 후 원할 때 아래 코드를 써서 타이머를 호출시키면 된다 NSRunLoop *runner = [NSRunLoop currentRunLoop]; [runner addTimer: t forMode: NSDefaultRunLoopMode]; -(void)onTick:(NSTimer *)timer { //do smth } <기타> 타이머에 userinfo를 통해 변수를 넘길때 autorelease된 변수를 넘기지 않도록 주의 timer에 target으로 넘겨준 객체는 retain된다. 명시적으로 timer를 release하지 않았을때 self도 dealloc되지 않으면서, memory leak이 발생할수 있다 [출처] NSTimer 사용법|작성자 아베
'iOS App Dev' 카테고리의 다른 글
NSString, NSDictionary정렬하기 (0) | 2011.12.29 |
---|---|
[스크랩] [펌] iOS와 멀티미디어 프로그래밍 (0) | 2011.12.24 |
AVAudioPlayer Class와 오디오 스트리밍 (0) | 2011.12.24 |
iOS 5에서 NSIndexPath 객체 사용 방법 변경 (0) | 2011.12.23 |
iPhone 4S vs iPhone 4 하드웨어 사양비교 (0) | 2011.12.08 |