ios開発のカウントダウン実現の2つの方法

1573 ワード

方法1:NSTimerを用いて実現
        主にNSTimerのscheduledTimerWithTimeIntervalメソッドを使用して1秒ごとにtimeFireMethod関数を実行し、timeFireMethodはカウントダウンのいくつかの操作を行い、完了時にtimerをinvalidateに落とすとokになります.コードは以下の通りです.
 secondsCountDown = 60;//60    
 countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
-(void)timeFireMethod{
	secondsCountDown--;
	if(secondsCountDown==0){
	  [countDownTimer invalidate];
	}
}

方法2:GCDで実現
コードは次のとおりです.
    __block int timeout=300; //     
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //     ,  
            dispatch_source_cancel(_timer);
            dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
		//                  
                。。。。。。。。
            });
        }else{
            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d %.2d         ",minutes, seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //                  
		。。。。。。。。
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);