导语: 新项目有差不多6个倒计时功能,以前都是在根tabbar的controller使用,所以一直也没注意这个问题。最近写的比较多,总结一下。
一、 NSTimer 的使用方法
@interface TimerViewController ()
@property (nonatomic, strong) NSTimer * timer;
@end
@implementation TimerViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerAction{
NSLog(@"timer run ---");
}
@end
总结来说, 就是三个步骤:
1、创建Timer
2、加入runloop
3、执行响应事件
系统提供了8个创建方法,6个类创建方法,2个实例化方法。
有三个方法直接将timer添加到了当前runloop default mode,而不需要我们自己操作,当然这个runloop只是当前的runloop,模式是default mode:
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
下面五种创建,不会自动添加到runloop,还需调用addTimer: forMode 添加到runloop。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
二、 NSTimer 和 VC 造成的循环引用
我们修改下上文中我们创建的TimerViewController文件:
@interface TimerViewController ()
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, assign) NSInteger increaseIndex;
@end
@implementation TimerViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.increaseIndex = 0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerAction{
NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}
- (void)dealloc{
[self.timer invalidate];
self.timer = nil;
NSLog(@"************ dealloc ***************");
}
@end
进入此页面后, 倒计时触发,timerAction方法开始执行。 点击返回按钮后, 不会触发 dealloc 方法, 内存无法释放。可以看见我们创建一个自增index, 第一次进入页面即可触发, 返回上个页面不会释放, 依然在打印值。再次进入页面触发了另一个timer方法, 同时打印两个index值。清晰的表明了, timer和 VC 循环引用导致了无法释放的问题。
即我们可以认为VC 持有 timer, 而timer的创建方法中参数target使得timer持有VC。
三、 NSTimer 手动销毁解决循环引用
我们继续改造上面的代码:
#import "TimerViewController.h"
@interface TimerViewController ()
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, assign) NSInteger increaseIndex;
@end
@implementation TimerViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton * tempBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
[tempBtn setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:tempBtn];
[tempBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
self.increaseIndex = 0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerAction{
NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}
- (void)btnClick{
[self.timer invalidate];
self.timer = nil;
}
- (void)dealloc{
[self.timer invalidate];
self.timer = nil;
NSLog(@"************ dealloc ***************");
}
@end
我们在页面返回之前提前点击创建的按钮,执行完 [self.timer invalidate]; self.timer = nil;方法后再进行pop操作。此次发现系统执行了dealloc方法,内存得以释放。 当然,这里只是做个例子来操作,真实情况可以放在类似于 viewWillDisappear:方法中进行销毁。
四、 NSTimer 使用弱引用解决Runloop和timer循环引用
既然是强引用造成的循环引用,那么我们将self弱引用不就可以了,理论上当然是可以了。 我们继续改造代码:
#import "TimerViewController.h"
@interface TimerViewController ()
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, assign) NSInteger increaseIndex;
@end
@implementation TimerViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.increaseIndex = 0;
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerAction{
NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}
- (void)dealloc{
[self.timer invalidate];
self.timer = nil;
NSLog(@"************ dealloc ***************");
}
@end
当我们 pop 出该页面以后,并没有调用dealloc方法,内存并没有得到释放,那么到底是什么原因呢?
在 本文的 NSTimer 的使用方法 段落中我们已经介绍了NSTimer的创建方案,无论如何创建。都会将NSTimer 加入到当前的RunLoop当中。所以RunLoop就持有该timer。即VC和timer相互引用,Runloop同时也引用timer。这也是我们在本文中 NSTimer 手动销毁解决循环引用 段落中除了[self.timer invalidate], 还要将 self.timer = nil的原因。
那么我们该如何解决这个问题呢?最简单的方案就是使用 YYKit 中的YYWeakProxy来处理。
继续修改代码:
#import "TimerViewController.h"
#import "YYWeakProxy.h"
@interface TimerViewController ()
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, assign) NSInteger increaseIndex;
@end
@implementation TimerViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.increaseIndex = 0;
YYWeakProxy * weakProxy = [YYWeakProxy proxyWithTarget:self];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakProxy selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)timerAction{
NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}
- (void)dealloc{
[self.timer invalidate];
self.timer = nil;
NSLog(@"************ dealloc ***************");
}
@end
此时我们pop后发现系统调用了dealloc方法,内存得以释放。
这里简单解释下YYWeakProxy的原理,YYWeakProxy源码:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface YYWeakProxy : NSProxy
@property (nullable, nonatomic, weak, readonly) id target;
- (instancetype)initWithTarget:(id)target;
+ (instancetype)proxyWithTarget:(id)target;
@end
NS_ASSUME_NONNULL_END
#import "YYWeakProxy.h"
@implementation YYWeakProxy
- (instancetype)initWithTarget:(id)target {
_target = target;
return self;
}
+ (instancetype)proxyWithTarget:(id)target {
return [[YYWeakProxy alloc] initWithTarget:target];
}
- (id)forwardingTargetForSelector:(SEL)selector {
return _target;
}
- (void)forwardInvocation:(NSInvocation *)invocation {
void *null = NULL;
[invocation setReturnValue:&null];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
return [NSObject instanceMethodSignatureForSelector:@selector(init)];
}
- (BOOL)respondsToSelector:(SEL)aSelector {
return [_target respondsToSelector:aSelector];
}
- (BOOL)isEqual:(id)object {
return [_target isEqual:object];
}
- (NSUInteger)hash {
return [_target hash];
}
- (Class)superclass {
return [_target superclass];
}
- (Class)class {
return [_target class];
}
- (BOOL)isKindOfClass:(Class)aClass {
return [_target isKindOfClass:aClass];
}
- (BOOL)isMemberOfClass:(Class)aClass {
return [_target isMemberOfClass:aClass];
}
- (BOOL)conformsToProtocol:(Protocol *)aProtocol {
return [_target conformsToProtocol:aProtocol];
}
- (BOOL)isProxy {
return YES;
}
- (NSString *)description {
return [_target description];
}
- (NSString *)debugDescription {
return [_target debugDescription];
}
@end
YYWeakProxy的代码非常简单,如果对NSProxy有一定认知的话
,就会发现是重载了父类的方法,将输入的target保存为实例变量,然后返回self。即YYWeakProxy对象会弱引用target对象,通过消息转发处理target事件,这样对应到NSTimer的使用上,就构成了这样的形式:
这样就避免了内存无法释放的问题,很好的解决了NSTimer的循环引用问题。