1.子线程中开启定时器
具体代码如下:
@interface ZGKTimerVC ()
@property (nonatomic, strong) NSTimer *timer;
// 要关闭的runloop, 要保持同一线程
@property (nonatomic, assign) CFRunLoopRef runloop;
// 记录子线程
@property (nonatomic, strong) NSThread *backgroundThread;
@end
@implementation ZGKTimerVC
- (void)viewDidLoad {
[super viewDidLoad];
// 子线程开启定时器
[NSThread detachNewThreadSelector:@selector(startTimerOnBackgroundThread) toTarget:self withObject:nil];
// 子线程上的定时器,必须要在子线程里面调用invalidate移除, 不要在主线程进行, 否则timer虽然停止了,但是runloop不会停止(每个子线程都有一个runloop, 需要找到对应线程关闭runloop)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (self.backgroundThread) {
[self performSelector:@selector(cancelTimer) onThread:self.backgroundThread withObject:nil waitUntilDone:NO];
}
});
}
// 在子线程中执行定时器
- (void)startTimerOnBackgroundThread{
NSLog(@"runloop start on backgroundThread");
// 子线程上的定时器,必须要在子线程里面invalidate, 不要在主线程进行, 否则timer虽然停止了,但是runloop不会停止
[self performSelector:@selector(cancelTimer) withObject:nil afterDelay:4.0];
[self startTimer];
// 停止了runloop才能执行
NSLog(@"runloop end on backgroundThread");
}
- (void)startTimer{
// 间隔之前先调用一次
[self timerAction];
// 方式一: 手动将timer放入runloop
// timerWithTimeInterval:在主线程执行timer,需要将timer手动添加到runloop中, 才会执行
self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
// runloop有两种模式, 分别是default和tracking
// 所以定时器要加到两种模式中, NSRunLoopCommonModes
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
// 方法二: 系统已经将timer加入到了runloop
// self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
// 子线程默认是关闭runloop的, 需要手动开启
// [[NSRunLoop currentRunLoop] run];
CFRunLoopRun();
}
- (void)timerAction{
static int num = 0;
NSLog(@"%d %@", num++, [NSThread currentThread]);
// 满足条件后,停止当前的运行循环
if (num == 10) {
// 一旦停止了运行循环,CFRunLoopRun()的后续代码能够执行,执行完毕后,线程被自动销毁
CFRunLoopStop(CFRunLoopGetCurrent());
}
}
- (void)cancelTimer{
NSLog(@"cancelTimer------");
[self.timer invalidate];
self.timer = nil;
}
- (void)dealloc{
NSLog(@"timerVc dealloc");
[self cancelTimer];
}
// 打印结果
2020-07-27 16:10:25.134929+0800 03-timer[2934:193644] runloop start on backgroundThread
2020-07-27 16:10:25.135111+0800 03-timer[2934:193644] 0 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:26.140051+0800 03-timer[2934:193644] 1 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:27.135630+0800 03-timer[2934:193644] 2 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:28.140374+0800 03-timer[2934:193644] 3 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:29.139387+0800 03-timer[2934:193644] cancelTimer------
2020-07-27 16:10:29.139609+0800 03-timer[2934:193644] runloop end on backgroundThread
注意点:
1.1 runloop在子线程是默认关闭的, 将定时器加入到runloop时,需要手动开启
1.2 停止定时器的方法有两种, 第一种是调用定时器的invalidate方法,将定时器移出runloop, runloop在没有输入源timer,就会自动停止, 线程销毁. 第二种,是调用CFRunLoopStop(CFRunLoopGetCurrent()), 直接停止runloop
1.3 显式开启runloop后, 会开启一个死循环, 要将runloop停止后,才能执行后续的代码,如: NSLog(@"runloop end on backgroundThread");
1.4 子线程上的定时器,必须要在子线程里面invalidate, 不要在主线程进行, 否则timer虽然停止了,但是runloop不会停止(每个子线程都有一个runloop, 需要找到对应线程关闭runloop), 如: 在主线程执行invalidate操作, timer随便停止了, 但是runloop的run方法后面的代码依旧没有执行
1.5 由于定时器是基于runloop的, 如果app存在大量运算时,定时器有时会不准确, 如果追求定时器的精确, 可以使用gcd的定时器.
1.6 创建timer时,self无论是正常的self还是weakSelf, 都会被timer强引用
2. 解决定时器的循环引用问题
2.1 使用带有block的timer构造法方法, 但是,这是iOS10推出的方法, 需要做兼容
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
2.2 通过timer的分类来实现解耦(模仿系统带block的timer)
@implementation NSTimer (NF)
+ (NSTimer *)nf_scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(block)block{
return [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(selectorMethod:) userInfo:[block copy] repeats:repeats];
}
+ (void)selectorMethod: (NSTimer *)timer{
block block = timer.userInfo;
if (block) {
block(timer);
}
}
2.3 使用NSProxy的消息转发机制来解耦
NS_ASSUME_NONNULL_BEGIN
@interface ZGKProxy : NSProxy
@property (nonatomic, weak) id target;
// 为了防止绑定target,最好调用这个工厂方法创建对象
+ (instancetype)allocWithTarget: (id)target;
@end
NS_ASSUME_NONNULL_END
#import "ZGKProxy.h"
@implementation ZGKProxy
+ (instancetype)allocWithTarget: (id)target{
ZGKProxy *proxy = [ZGKProxy alloc];
proxy.target = target;
return proxy;
}
#pragma mark - 这个函数抛出一个函数的签名,再由后面的forwardInvocation:去执行,为给定消息提供参数类型信息
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
// sel => 调用的方法名, 即控制器的timerAction方法
return [self.target methodSignatureForSelector:sel];
}
#pragma mark - NSInvocation封装了NSMethodSignature, 通过invokeWithTarget:方法将消息转发给其他对象,由被转发的对象执行该消息方法
- (void)forwardInvocation:(NSInvocation *)invocation{
[invocation invokeWithTarget:self.target];
}
@end
#import "ZGKTimerVC.h"
#import "ZGKProxy.h"
@interface ZGKTimerVC ()
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation ZGKTimerVC
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"NSProxy实现解耦";
self.view.backgroundColor = UIColor.whiteColor;
// 使用NSProxy消息转发机制,进行解耦
ZGKProxy *proxy = [ZGKProxy allocWithTarget:self];
// 如果没有设置target,则proxy进行函数签名的时候, 会直接crash
/*
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSProxy doesNotRecognizeSelector:timerAction] called!'
*/
// proxy.target = self;
self.timer = [NSTimer timerWithTimeInterval:1.0 target:proxy selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerAction{
NSLog(@"执行定时器任务");
}
- (void)dealloc{
NSLog(@"%s", __func__);
[self.timer invalidate];
self.timer = nil;
}
@end
这里需要特别注意的是:
2.3.1 proxy必须重写函数签名方法methodSignatureForSelector:和消息转发方法forwardInvocation:
2.3.2 绑定target对象, 如果没有绑定target会直接造成crash.
2.3.3 proxy的属性target, 必须是weak, 才能解耦