導(dǎo)語: 新項(xiàng)目有差不多6個倒計時功能浪汪,以前都是在根tabbar的controller使用巴柿,所以一直也沒注意這個問題。最近寫的比較多死遭,總結(jié)一下广恢。
一、 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
總結(jié)來說呀潭, 就是三個步驟:
1钉迷、創(chuàng)建Timer
2至非、加入runloop
3、執(zhí)行響應(yīng)事件
系統(tǒng)提供了8個創(chuàng)建方法糠聪,6個類創(chuàng)建方法荒椭,2個實(shí)例化方法。
有三個方法直接將timer添加到了當(dāng)前runloop default mode舰蟆,而不需要我們自己操作趣惠,當(dāng)然這個runloop只是當(dāng)前的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;
下面五種創(chuàng)建身害,不會自動添加到runloop味悄,還需調(diào)用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 造成的循環(huán)引用
我們修改下上文中我們創(chuàng)建的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
進(jìn)入此頁面后, 倒計時觸發(fā)侍瑟,timerAction方法開始執(zhí)行。 點(diǎn)擊返回按鈕后, 不會觸發(fā) dealloc 方法, 內(nèi)存無法釋放丙猬≌茄眨可以看見我們創(chuàng)建一個自增index, 第一次進(jìn)入頁面即可觸發(fā), 返回上個頁面不會釋放, 依然在打印值。再次進(jìn)入頁面觸發(fā)了另一個timer方法, 同時打印兩個index值茧球。清晰的表明了, timer和 VC 循環(huán)引用導(dǎo)致了無法釋放的問題咐低。
即我們可以認(rèn)為VC 持有 timer, 而timer的創(chuàng)建方法中參數(shù)target使得timer持有VC袜腥。
三、 NSTimer 手動銷毀解決循環(huán)引用
我們繼續(xù)改造上面的代碼:
#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
我們在頁面返回之前提前點(diǎn)擊創(chuàng)建的按鈕钉汗,執(zhí)行完 [self.timer invalidate]; self.timer = nil;方法后再進(jìn)行pop操作羹令。此次發(fā)現(xiàn)系統(tǒng)執(zhí)行了dealloc方法,內(nèi)存得以釋放损痰。 當(dāng)然福侈,這里只是做個例子來操作,真實(shí)情況可以放在類似于 viewWillDisappear:方法中進(jìn)行銷毀卢未。
四肪凛、 NSTimer 使用弱引用解決Runloop和timer循環(huán)引用
既然是強(qiáng)引用造成的循環(huán)引用,那么我們將self弱引用不就可以了辽社,理論上當(dāng)然是可以了伟墙。 我們繼續(xù)改造代碼:
#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
當(dāng)我們 pop 出該頁面以后,并沒有調(diào)用dealloc方法滴铅,內(nèi)存并沒有得到釋放戳葵,那么到底是什么原因呢?
在 本文的 NSTimer 的使用方法 段落中我們已經(jīng)介紹了NSTimer的創(chuàng)建方案汉匙,無論如何創(chuàng)建拱烁。都會將NSTimer 加入到當(dāng)前的RunLoop當(dāng)中生蚁。所以RunLoop就持有該timer。即VC和timer相互引用戏自,Runloop同時也引用timer邦投。這也是我們在本文中 NSTimer 手動銷毀解決循環(huán)引用 段落中除了[self.timer invalidate], 還要將 self.timer = nil的原因。
那么我們該如何解決這個問題呢擅笔?最簡單的方案就是使用 YYKit 中的YYWeakProxy來處理志衣。
繼續(xù)修改代碼:
#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后發(fā)現(xiàn)系統(tǒng)調(diào)用了dealloc方法,內(nèi)存得以釋放剂娄。
這里簡單解釋下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有一定認(rèn)知的話
阅懦,就會發(fā)現(xiàn)是重載了父類的方法和二,將輸入的target保存為實(shí)例變量,然后返回self耳胎。即YYWeakProxy對象會弱引用target對象惯吕,通過消息轉(zhuǎn)發(fā)處理target事件,這樣對應(yīng)到NSTimer的使用上怕午,就構(gòu)成了這樣的形式:
這樣就避免了內(nèi)存無法釋放的問題废登,很好的解決了NSTimer的循環(huán)引用問題。