iOS - Swift NSTimer 定时器


前言

	public class NSTimer : NSObject
  • 作用
    • 在指定的时间执行指定的任务。
    • 每隔一段时间执行指定的任务。

1、定时器的创建

  • 当定时器创建完(不用 scheduled 的,添加到 runloop 中)后,该定时器将在初始化时指定的 ti 秒后自动触发。

  • scheduled 方式:

    • 创建并启动定时器。

    • 默认将时钟以 NSDefaultRunLoopMode 模式添加到运行循环。

    • 发生用户交互的时候,时钟会被暂停。

      	/*
      		public class func scheduledTimerWithTimeInterval(ti: NSTimeInterval, 
      		                                     target aTarget: AnyObject, 
      		                                 selector aSelector: Selector, 
      		                                           userInfo: AnyObject?, 
      		                                    repeats yesOrNo: Bool) -> NSTimer
      		 
      		参数:
      			TimeInterval:触发时间,单位秒
      			target:定时起触发对象
      			selector:定时器响应方法
      			userInfo:用户信息
      			repeats:是否重复执行,YES 每个指定的时间重复执行,NO 只执行一次
      	*/
      
      	// 创建并启动定时器
      	let timer:NSTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, 
      	                                                    target: self, 
      	                                                  selector: #selector(ViewController.updateTimer(_:)), 
      	                                                  userInfo: nil, 
      	                                                   repeats: true)
      
  • timer 方式:

    • 创建定时器,添加到运行循环后启动定时器。

    • 将时钟以指定的模式添加到运行循环。

      	/*
      		+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti 
      		                            target:(id)aTarget 
      		                          selector:(SEL)aSelector 
      		                          userInfo:(nullable id)userInfo 
      		                           repeats:(BOOL)yesOrNo;
      	
      		- (void)addTimer:(NSTimer *)timer forMode:(NSString *)mode;
      
      		mode:
          		NSDefaultRunLoopMode: 时钟,网络。           发生用户交互的时候,时钟会被暂停
          		NSRunLoopCommonModes: 用户交互,响应级别高。  发生用户交互的时候,时钟仍然会触发,如果时钟触发方法非常
                                                              耗时,使用此方式时用户操作会造成非常严重的卡顿。
      	*/
      	
      	// 创建定时器
      	let timer:NSTimer = NSTimer(timeInterval: 2.0, 
      	                                  target: self, 
      	                                selector: #selector(ViewController.updateTimer(_:)), 
      	                                userInfo: nil, 
      	                                 repeats: true)
      	
      	// 将定时器添加到运行循环
      	NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
      

2、定时器的启动与关闭

	// 启动定时器
	timer.fireDate = NSDate.distantFuture()
	    
	// 暂停定时器
	timer.fireDate = NSDate.distantPast()
	    
	// 关闭定时器,永久关闭定时器
	timer.invalidate()

3、子线程定时器的创建

  • 在子线程创建定时器时,需要手动开启子线程的运行循环。

    	dispatch_async(dispatch_get_global_queue(0, 0)) { 
        
        	// 在子线程创建定时器
        	/*
            	scheduled 或 timer 方式创建
        	*/
        	let timer:NSTimer = NSTimer(timeInterval: 2.0, 
        	                     target: self, 
        	                   selector: #selector(ViewController.updateTimer(_:)), 
        	                   userInfo: nil, 
        	                    repeats: true)
        	NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
        
        	// 启动子线程的运行循环
        	/*
            	这句代码就是一个死循环!如果不停止运行循环,不会执行添加到此句之后的任何代码
        	*/
        	CFRunLoopRun()
        
        	// 停止子线程运行循环之前,不会执行添加到此处的任何代码
    	}
    
    	var num:Int = 0
    
    	func updateTimer(timer:NSTimer) {
        
        	num  = num + 1
        
        	// 满足条件后,停止当前的运行循环
        	if (num == 8) {
            
            	// 停止当前的运行循环
            	/*
                	一旦停止了运行循环,后续代码能够执行,执行完毕后,线程被自动销毁
            	*/
            	CFRunLoopStop(CFRunLoopGetCurrent())
        	}
    	}
    

4、定时任务

  • 1)performSelector

    	// 延时调用
    	/*
    		1.5 秒后自动调用 self 的 hideHUD 方法
    	*/
    	self.performSelector(#selector(NsTimer.hideHUD), withObject: nil, afterDelay: 1.5)
    	    
    	// 取消延时调用
    	NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(NsTimer.hideHUD), object: nil)
    
  • 2)GCD

    	// 多线程
    	/*
    	    1.5 秒后自动执行 block 里面的代码
    	*/
    	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
    	    
    	    self.hud.alpha = 0.0;
    	}
    
  • 3)NSTimer

    	// 定时器
    	/*
    		1.5 秒后自动调用 self 的 hideHUD 方法
    	*/
    	NSTimer.scheduledTimerWithTimeInterval(1.5, 
    	                                target: self, 
    	                              selector: #selector(NsTimer.hideHUD), 
    	                              userInfo: nil, 
    	                               repeats: false)
    


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM