IOS 添加定时器(NSTimer)

 定时器

CADisplayLink:时间间隔比较小(使用时间频率高)的时候用(适合小游戏中开发)

NSTimer:时间间隔比较大的时候调用(适合图片轮放的时候用)


//声明定时器

@property (nonatomic,strong) NSTimer *timer;


/*
* * 添加定时器 */ - (void)addTimer { self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES]; //NSRunLoop可以优先级处理些定时器(线程优先)
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/**
 *  移除定时器
 */
- (void)removeTimer
{
    [self.timer invalidate];//设置定时器无效
    self.timer = nil;
}

 调用代理时 定时器 事例:


#pragma  mark -代理方法


/*
* 当scrollView正在滚动就会调用 */ -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ //根据scrollView的滚动位置决定pageControl显示第几页 CGFloat scrollW=self.scrollView.frame.size.width; int page=(scrollView.contentOffset.x+scrollW*0.5)/scrollW; self.pageControl.currentPage=page; } /** 开始拖拽的时候调用 */ -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { //停止定时器(一旦定时器停止了,就不能再使用) [self removeTimer]; } /**停止拖拽的时候调用*/ -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { //开启定时器 [self addTimer]; }
原文地址:https://www.cnblogs.com/liuwj/p/6426510.html