说到定时器 也许大家并不陌生,可能大家都只是对NSTimer比较熟悉吧,那么久来为大家介绍另外两种不常见的方法吧
1.NSTimer(详细的就不给大家介绍了)
+ (NSTimer*)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation*)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer*)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullableid)userInfo repeats:(BOOL)yesOrNo;
注意:上面俩方法创建的timer需要将timer注册到NSRunloop中才能开启定时器的功能
[[NSRunLoop currentRunLoop] addTimer:timer:forMode:NSRunLoopCommonModes];
+ (NSTimer*)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullableid)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer*)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation*)invocation repeats:(BOOL)yesOrNo;
ps:默认将timer添加到当前runloop中了,所有无需添加
2. dispatch_source_create()
简单地分为几个步骤 下面慢慢来讲解
注意:这里创建的timer并需要设置为全局属性,因为GCD会自动管理内存,当回收的时候,你发现timer不起作用,就很尴尬了😂
@property (nonamatic , strong ) dispatch_source_t timer;
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC );
dispatch_source_set_event_handler(_timer, ^{
flag ++;
NSLog(@"flag = %d",flag);
});
添加执行事件代码。
dispatch_resume(_timer);
手动触发
3.CADisplayLink
CADispalyLink displayLink = [CADisplayLink displayLinkWithTarget:selfselector:@selector(handleDisplayLink:)];
[displayLink addToRunLoop:[NSRunLoopcurrentRunLoop] forMode:NSDefaultRunLoopMode];
较为精准,与屏幕刷新帧率同步,多用户视图渲染或绘图
网友评论