2012-02-04 2 views
1

여기에 제 코드가 있습니다. 타이머가 시작된 후 5 초 만에 타이머가 멈출 것으로 예상했으나 그렇지 않습니다. 여기서 뭐가 잘못 됐니?NSTimer 코드가 영원히 실행 중입니다

-(void)loadView 
{ 
NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]; 



NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.0 
           target:self 
           selector:@selector(targetMethod:) 
           userInfo:nil 
           repeats:YES]; 
if([NSDate timeIntervalSinceReferenceDate] - startTime >= 5) { 
    [timer invalidate]; 
} 

} 

-(void)targetMethod:(NSTimer *)timer { 


    NSLog(@"bla"); 
} 
+0

. 무엇을하려고합니까? – Costique

+0

targetMethod를 추가하는 것을 잊었습니다. 업데이트 된 버전을 확인하십시오. – objlv

답변

2

있는 NSDate의 timeIntervalSinceReferenceDate는 항상있을 것 같은 값을 빼면, 2001 년 1 월 1 일을 반환 기본적으로 0입니다

애플의 문서 : 여기 https://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

는 생각 : 당신의 .H에서

당신의하는 .m에서
@interface MyClass : NSObject 

@property (nonatomic, retain) NSTimer *timer; 

- (void)targetMethod:(NSTimer *)timer; 
- (void)cancelTimer; 

@end 

@implementation MyClass 

@synthesize timer; 

-(void)loadView 
{ 
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.0 
              target:self 
              selector:@selector(targetMethod:) 
              userInfo:nil 
              repeats:YES]; 
    [self performSelector:@selector(cancelTimer) withObject:nil afterDelay:5.0]; 
} 

-(void)cancelTimer { 
    [self.timer invalidate]; 
} 

-(void)targetMethod:(NSTimer *)timer { 
    NSLog(@"bla"); 
} 
+0

글쎄, 시작한 지 5 초 후 타이머를 멈추게하려면 어떻게해야할까요? – objlv

+0

코드를 삽입하여 시연합니다. startTime은 NSTimeInterval과 같이 클래스의 속성이어야합니다. –

+0

나는 당신의 코드를 시도했지만, 여전히 bla 문자열을 영원히 출력한다. 타이머가 멈추지 않아. – objlv

0

시간 차이는 항상 0이므로 절대 무효화하지 마십시오!

타이머를 설정하기 전에 startTime을 설정하십시오.

+0

여전히 작동하지 않습니다. 업데이트 된 코드 – objlv

+0

을 참조하십시오. 속성 변수에 startTime이 필요합니다. 그리고 귀하의 타이머 코드는 targetMethod :라는 메서드에 배치해야합니다. – peterept

0

'startTime'값을 얻으면 비교할 값이 동일합니다. 계산 결과는 항상 0이됩니다. loadView 메소드에 'startTime'을 저장 한 다음 계산에 사용해야합니다.

1

이 짧고 간단하다`어떤 이해가되지 않습니다 : 당신은`targetMethod의 코드가 있기 때문에 NSTimer`의 작동 방식을`오해하는 것

NSDate *endtime = [NSDate dateWithTimeIntervalSinceNow:5]; 
[NSTimer scheduledTimerWithTimeInterval:1 
     target:self 
     selector:@selector(timerTick:) 
     userInfo:endtime 
     repeats:YES]; 


-(void)timerTick:(NSTimer*)timer 
{ 
    NSLog(@"timer tick"); 
    if ([timer.userInfo timeIntervalSinceNow] < 0) 
    { 
     [timer invalidate]; 
     NSLog(@"invalidating timer"); 
    } 
} 
관련 문제