2012-02-04 8 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です。

Appleのドキュメント:ここ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"); 
    } 
} 
関連する問題