2013-07-26 2 views
0

특정 스레드에서 실행 루프에 타이머를 연결하지만 타이머가 트리거되기 전에 스레드가 종료되어 메소드가 실행되지 않을 수 있습니다. 이 시나리오가 가능합니까?지연 호출이 스레드에서 절대로 호출되지 않을 수 있습니까?

+1

@MarcusAdams 요청한 시간이 지나면 이벤트 루프를 통해 다음 번에 타이머가 실행됩니다. 다음 번에 끝날 때까지 결코 지연되지 않습니다. – bbum

+0

@bbum, 타이머를 반복 할 생각이었습니다. 타이머 이벤트가 너무 지연되면 건너 뛸 수 있습니다. 내 의견을 삭제했습니다. "지연된 통화"는 타이머를 반복하는 것에 대한 이야기가 아닙니다. :) –

+0

@MarcusAdams 아 .. 좋아. 내 오해. 코드 그림의 경우 – bbum

답변

3

분명히 가능하며 입증하기 쉽습니다.

#import <Foundation/Foundation.h> 

#define TIMER_INTERVAL 2.0 

@interface Needle : NSObject 

- (void)sew; 
- (void)tick:(NSTimer *)tim; 

@end 

@implementation Needle 
{ 
    NSTimer * tim; 
} 

- (void)sew 
{ 
    @autoreleasepool{ 
     tim = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL 
               target:self 
              selector:@selector(tick:) 
              userInfo:nil 
               repeats:NO]; 

     while(![[NSThread currentThread] isCancelled]){ 
      [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]]; 
     } 
    } 
} 

- (void)tick:(NSTimer *)timer 
{ 
    NSLog(@"Let's get the bacon delivered!"); 
    [[NSThread currentThread] cancel]; 
} 

@end 

int main(int argc, const char * argv[]) 
{ 

    @autoreleasepool { 

     Needle * needle = [Needle new]; 
     NSThread * thread = [[NSThread alloc] initWithTarget:needle 
                selector:@selector(sew) 
                 object:nil]; 

     [thread start]; 
     // Change this to "+ 1" to see the timer fire. 
     NSTimeInterval interval = TIMER_INTERVAL - 1; 
     [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:interval]]; 
     [thread cancel]; 

    } 
    return 0; 
} 
+0

+1. – Boon

0

예, 주 스레드가 아닌 경우 NSRunLoop은 스레드를 활성 상태로 유지하고 타이머를 연결합니다. 하나를 만들고 실행시켜야합니다.

0

예입니다. 이것은 타이머가 있지만 앱이 "조기에"종료되면 아주 쉽게 발생합니다. 이 경우 이전에 설정 한 타이머의 시작 날짜 이전에 앱이 다시 시작될 때에도 타이머의 시작 날짜가 손실됩니다.