iOS 定时器

CADispalyLink

计时器对象,与屏幕的刷新率同步。

iOS设备的屏幕刷新频率是固定的,其精度相当准确,一般用于做UI界面的不停重绘。

CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(run)];
    //设置 CADisplayLink selector 调用时间间隔
    displayLink.preferredFramesPerSecond = 1;
    //添加到 runloop,并指定 RunloopMode
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  //暂停
    [displayLink setPaused:YES];
    //停止使用
    [displayLink invalidate];

NSTimer

NSTimer的使用

NSTimer比较常用的创建方法有以下两种:

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

scheduledTimerWithTimeInterval在主线程创建的定时器会在创建后自动将timer添加到主线程的RunLoop中并启动,主线程的RunLoopMode为NSDefaultRunLoopMode,如果有滚动视图并滑动的时候,执行的是UITrackingRunLoopMode,NSDefaultRunLoopMode被挂起,定时器失效,等到滑动结束才恢复。
因此需要将timer分别加入UITrackingRunLoopModeNSDefaultRunLoopMode中:

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];

或者直接添加到 NSRunLoopCommonModes中:

[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

也可以新开一个子线程,主线程的RunLoop默认是开启的,子线程的RunLoop需要手动开启:

[NSThread detachNewThreadWithBlock:^{
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
            NSLog(@"111");
        }];
        [[NSRunLoop currentRunLoop] run];
    }];
    //如果使用 timerWithTimeInterval创建,创建的定时器不会直接启动, 需要手动添加到RunLoop中
    [NSThread detachNewThreadWithBlock:^{
        self.timer = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
            NSLog(@"111");
        }];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        [[NSRunLoop currentRunLoop] run];
    }];

NSTimer循环引用的解决方法

创建中间类解决

创建个继承自NSObject的类

@interface LWTProxy : NSObject

+ (instancetype)proxyWithTarget:(id)target;
@property (nonatomic, weak)id target;

@end

#import "LWTProxy.h"
#import <objc/runtime.h>

@implementation LWTProxy

+ (instancetype)proxyWithTarget:(id)target {
    LWTProxy *proxy = [[LWTProxy alloc] init];
    proxy.target = target;
    return proxy;
}

//消息转发
- (id)forwardingTargetForSelector:(SEL)aSelector {
    return self.target;
}

@end

使用

//添加个中间对象,解决timer的循环引用问题
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[LWTProxy proxyWithTarget:self] selector:@selector(run) userInfo:nil repeats:YES];

也可以使用NSProxy来解决循环引用。
创建一个继承自NSProxy的类,

使用 block 来解决

创建一个 NSTimer (Weak)

@interface NSTimer (Weak)
+ (NSTimer *)weak_scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats;
+ (NSTimer *)weak_timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void(^)())block;

@end


@implementation NSTimer (Weak)
+ (NSTimer *)weak_scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats {
    NSTimer *t = [self scheduledTimerWithTimeInterval:interval
                                               target:self
                                             selector:@selector(_invoke:)
                                             userInfo:[block copy]
                                              repeats:repeats];
    return t;
}

+ (NSTimer *)weak_timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void(^)())block {
    NSTimer * t = [self timerWithTimeInterval:interval
                                       target:self
                                     selector:@selector(_invoke:)
                                     userInfo:[block copy]
                                      repeats:repeats];
    return t;
}

+ (void)_invoke:(NSTimer *)timer {
    void (^_block)() = timer.userInfo;
    if (_block) {
        _block();
    }
}

@end

使用时需注意,先定义了一个弱引用,令其指向self,然后使块捕获这个引用,而不直接去捕获普通的self变量。也就是说,self不会为计时器所保留。当块开始执行时,立刻生成strong引用,以保证实例在执行期间持续存活。


__weak XXClass *weakSelf = self;
self.timer = [NSTimer weak_scheduledTimerWithTimeInterval:1.0 block:^{
       XXClass *strongSelf = weakSelf;
       [strongSelf doSomething];
    } repeats:YES];

NSTimer为什么不准

情况产生:
1、NSTimer被添加在mainRunLoop中,模式是NSDefaultRunLoopMode,mainRunLoop负责所有主线程事件,例如UI界面的操作,复杂的运算使当前RunLoop持续的时间超过了定时器的间隔时间,那么下一次定时就被延后,这样就会造成timer的阻塞、2:模式的切换,当创建的timer被加入到NSDefaultRunLoopMode时,此时如果有滑动UIScrollView的操作,runLoop 的mode会切换为TrackingRunLoopMode,这时timer会停止回调。

GCD定时器

GCD 定时器比 NSTimer 更精确,定时器一定要被强引用,不然会被释放,导致的定时器无效。

创建一个GCD定时器LWTTimer

@interface LWTTimer : NSObject
//方法一
+ (NSString *)exeTask:(void(^)(void))task
        start:(NSTimeInterval)start
        interval:(NSTimeInterval)interval
        repeats:(BOOL)repeats async:(BOOL)async;

//方法二
+ (NSString *)exeTask:(id)target
        selector:(SEL)selector
        start:(NSTimeInterval)start
        interval:(NSTimeInterval)interval
        repeats:(BOOL)repeats async:(BOOL)async;

+ (void)cancelTask:(NSString *)taskName;

@end


@implementation LWTTimer

static NSMutableDictionary *timers;
dispatch_semaphore_t semaphore_;

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        timers = [NSMutableDictionary dictionary];
    });
    
    //因为可能会在多个线程都调用这个timer,全局字典不能同时存、取,所以要加锁
    semaphore_ = dispatch_semaphore_create(1);
    
}

+ (NSString *)exeTask:(void(^)(void))task
        start:(NSTimeInterval)start
        interval:(NSTimeInterval)interval
        repeats:(BOOL)repeats async:(BOOL)async {
    
    if (!task || start < 0 || (interval <= 0 && repeats)) return nil;
  
    
    //创建队列
    dispatch_queue_t queue = async ? dispatch_queue_create("timer", DISPATCH_QUEUE_SERIAL) : dispatch_get_main_queue();

    //创建定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    //设置时间
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, start * NSEC_PER_SEC, interval * NSEC_PER_SEC);
    
    //加锁
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
    //定时器的唯一标识
    NSString *name = [NSString stringWithFormat:@"%lu",(unsigned long)timers.count];
    //存放到字典中,还可以使timer产生强引用
    timers[name] = timer;
    dispatch_semaphore_signal(semaphore_);

    //设置回调
    dispatch_source_set_event_handler(timer, ^{
        task();
        
        if (!repeats) {
            //不重复的任务
            [self cancelTask:name];
        }
    });
    
    //启动定时器
    dispatch_resume(timer);
    
    
    
    return name;
    
}

+ (NSString *)exeTask:(id)target
        selector:(SEL)selector
        start:(NSTimeInterval)start
        interval:(NSTimeInterval)interval
              repeats:(BOOL)repeats async:(BOOL)async {
    return [self exeTask:^{
        //消除xcode警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [target performSelector:selector];
#pragma clang diagnostic pop
    } start:start interval:interval repeats:repeats async:async];
}

+ (void)cancelTask:(NSString *)taskName {
    
    if (taskName.length == 0) return;
    
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
    
    dispatch_source_t timer = timers[taskName];
    if (timer) {
        dispatch_source_cancel(timer);
        [timers removeObjectForKey:taskName];
    }

    dispatch_semaphore_signal(semaphore_);
}


@end

使用:

self.timerName = [LWTTimer exeTask:^{
        NSLog(@"timer-%@",[NSThread currentThread]);
    } start:2.0 interval:1.0 repeats:YES async:NO];


//停止定时器
[LWTTimer cancelTask:self.timerName];
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容