2015-06-10 58 views
-1

我知道如何啓動NSTimer,並且我給出了代碼,但現在我想在3或4分鐘後停止NSTimer,但我該如何做到這一點NSTimer每2秒啓動和調用方法並在3分鐘後停止

我懂得放棄的NSTimer,但如何停止3分鐘後 需要一些幫助

NSTimer* myTimer; 
    myTimer= [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self 
                 selector: @selector(updateUIinMainThread:) userInfo: nil repeats: YES]; 

回答

0

聲明:

int totalSeconds; 
NSTimer *twoMinTimer; 

代碼:

- (void)timer { 
    totalSeconds--; 

    if (totalSeconds == 0) { 
     [twoMinTimer invalidate]; 
     //Timer stops after 2 minute from this you can do your stuff here 
    } 
} 

- (void)viewWillAppear:(BOOL)animated{ 
    [super viewWillAppear:animated]; 
    totalSeconds = 120; 
    twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                target:self 
               selector:@selector(timer) 
               userInfo:nil 
                repeats:YES]; 
} 

希望這有助於

+0

int值的totalseconds? – Thanks

+0

這真的很棒非常感謝 – Thanks

+0

@Thanks隨時歡迎:) –

1

保存時,計時器開始的時刻

NSTimer* myTimer; 
myTimer= [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self 
                selector: @selector(updateUIinMainThread:) userInfo: nil repeats: YES]; 
savedTime = [NSDate date]; 

和功能updateUIinMainThread:將當前時間與保存時間進行比較。如果結果大於180秒,請停止定時器。

-(void)updateUIinMainThread:(NSTimer *)timer 
{ 
    NSDate *timeNow = [NSDate date]; 
    NSTimeInterval timespan = [timeNow timeIntervalSinceDate:savedTime]; 
    if(timesapn>180) 
    { 
     [timer invalidate]; 
    } 
} 
+0

我不擅長NSDate請求給我現在的代碼我想提交應用程序到應用程序商店 – Thanks

+0

我想在180次之後無效 – Thanks

+0

@Thanks檢查更新。 –

0

可能是下面的代碼將幫助您:

第1步:申報以下實例變量

@interface yourclass:NSObject的 {

NSTimer* myTimer; 
NSDate *initialDate; 

}

第2步:在您的類中創建myTimer您想:

myTimer= [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(callByTimer) userInfo:nil repeats:YES]; 

第3步:實現callByTimer方法:

- (void)callByTimer{ 
// get initial date at very first call by myTimer 

if (!initialDate) 
{ 
    initialDate = [NSDate date]; 
} 

// get current date 
NSDate *currentDate = [NSDate date]; 

// get seconds between currentdate and initial date 
NSTimeInterval secondsBetween = [currentDate timeIntervalSinceDate:initialDate]; 

// convert seconds into minutes 
NSInteger minutes = secondsBetween/60; 

// check if minutes is greater than or equal to 3 then invalidate myTimer and assign nil to initialDate variable 
if (minutes>=3) 
{ 
    [myTimer invalidate]; 
    initialDate = nil; 
}}