Skip to content

Instantly share code, notes, and snippets.

@zhangkn
Last active May 4, 2018 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangkn/1d4cc343a19c95b5902cd3d40c298504 to your computer and use it in GitHub Desktop.
Save zhangkn/1d4cc343a19c95b5902cd3d40c298504 to your computer and use it in GitHub Desktop.
创建NSTimer对象
//方式一: 使用scheduledTimerWithTimeInterval:创建NSTimer
NSTimer *timer ;
%hook SpringBoard
//applicationDidFinishLaunching
-(void)applicationDidFinishLaunching: (id)application
{
%orig;
//自动添加到`NSDefaultRunLoopMode`中去执行
timer = [NSTimer scheduledTimerWithTimeInterval:6*2 target:self selector:@selector(checkHeart) userInfo:nil repeats:YES];
//当然你也可以在iOS10.0之后的系统使用Block 替代selector。我比较喜欢使用block
}
%new
- (void)checkHeart
{
//定时检测微信是否开启
[[UIApplication sharedApplication] launchApplicationWithIdentifier:@"com.tencent.xin" suspended:0];
}
%end
//方式二:使用timerWithTimeInterval:创建
// 创建NSTimer对象
NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
// 加入RunLoop中
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//note: `UIScrollView` 滑动时执行的是 `UITrackingRunLoopMode`,`NSDefaultRunLoopMode`被挂起,会导致定时器失效,等恢复为**滑动结束**时才恢复定时器
//解决方案:在 `UIScrollView` 拖动时也不影响
// 1)**timer**分别添加到 `UITrackingRunLoopMode` 和 `NSDefaultRunLoopMode`中
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop mainRunLoop] addTimer:timer forMode: UITrackingRunLoopMode];
//2)直接将**timer**添加到`NSRunLoopCommonModes` 中
[[NSRunLoop mainRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];
//-------释放方法:-----
// 停止定时器
[timer invalidate];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment