(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;
}
}
网友评论