美文网首页
创建定时器

创建定时器

作者: Jean_Lina | 来源:发表于2020-08-29 18:27 被阅读0次
     (1) NSTimer创建定时器:
    @property (nonatomic, strong) NSTimer *timer;
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            self.timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
            [self.timer fire];
        }
        return self;
    }
    - (void)updateTimer {
        NSLog(@"定时器计时开始");
    }
    - (void)cleanTimer {
        [self.timer invalidate];
        //self.timer = nil;
    }
    
     (2)CADisplayLink创建定时器:
    @property (nonatomic, strong)CADisplayLink *displayLink;
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateTime)];
            self.displayLink.frameInterval = 0.5;
            [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        }
        return self;
    }
    - (void)updateTime {
        NSLog(@"定时器计时开始");
    }
    - (void)cleanTimer {
        [self.displayLink invalidate];
    }
    
    (3) dispatch_source_t创建定时器:
    @property (nonatomic, strong) dispatch_source_t timer;
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            count = 0;
            self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
            dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
            uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
            dispatch_source_set_timer(self.timer, start, interval, 0);
            //设置事件处理回调
            dispatch_source_set_event_handler(self.timer, ^{
                NSLog(@"定时器计时开始");
            });
            //启动定时器
            dispatch_resume(self.timer);
        }
        return self;
    }
    - (void)cleanTimer {
        if (self.timer) {
            dispatch_source_cancel(self.timer);
            //self.timer = nil;
        }
    }
    

    相关文章

      网友评论

          本文标题:创建定时器

          本文链接:https://www.haomeiwen.com/subject/bqyjsktx.html