一 NSTimer的普通用法及其问题
用法
- (void)addNormalTimer
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(logInfo:) userInfo:@"NormalTimer" repeats:YES];
}
- (void)logInfo:(NSTimer *)timer
{
NSLog(@"logInfo %@", timer.userInfo);//logInfo NormalTimer
}
问题
当从当前界面跳转到其他界面的时候控制台还是源源不断地在输出logInfo NormalTimer
,这说明NSTimer
还在工作。
比较容易想到的方法就是在dealloc
方法里添加invalidate
方法
- (void)dealloc
{
[_timer invalidate];
NSLog(@"dealloc");
}
再次运行发现NSTimer
还是没有停止,dealloc
方法也进不来
分析一下为什么会出现这样的问题
1 Runloop
强引用了NSTimer
对象
Note in particular that run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.
2 NSTimer
对象强引用了target
(示例中就是视图控制器)
Target is the object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated.
3 因为target
一直被强引用着,所以它不会被销毁,也就不会触发dealloc
方法。
提到强引用自然会想到弱引用,如果把target
设成弱引用,会不会就能解决问题呢?
- (void)addNormalTimer
{
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target: weakSelf selector:@selector(logInfo:) userInfo:@"NormalTimer" repeats:YES];
}
通过运行发现,使用弱引用也不能解决问题。这里weak
和strong
的唯一区别就是如果视图控制器在NSTimer
对象运行期间被释放了,NSTimer
对象的target会变成nil。这里有更详细的解释
二 解决方法
方法1 : 提前调用invalidate方法
在合适的时候调用NSTimer
对象的invalidate
方法,比如在viewDidDisappear
方法里面调用,但是viewDidDisappear
方法有可能是在该视图控制器pop
的时候调用,也有可能是在push
另外一个视图控制器的时候调用。如果只是想在销毁该视图控制器之前(pop
)让NSTimer
停止工作,那么可以在调用pop
方法之前调用NSTimer
对象的invalidate
方法即可。
方法2 : 使用自定义类
既然不能通过weakSelf
来解决问题,那么我们可以给NSTimer
一个假的target
,这个target
有一个指向视图控制器的弱引用
,这样的话视图控制器就能被正常销毁了。
示例中用到了2个类
-
JCAutoInvalidateTimer
: 代替NSTimer
类来创建NSTimer实例
-
JCAutoInvalidateTimerTarget
: 前面提到的假target
,由于这个类不需要调用者知道
,所以没有新建对应的.h和.m文件,而是放到了JCAutoInvalidateTimer.m
文件中
使用
1 使用下面的第一个方法会在合适的时间自动调用NSTimer的invalidate方法,所以使用起来非常简单
[JCAutoInvalidateTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(logInfo:) userInfo:@"JCTimer" repeats:YES];
2 如果使用下面的第二个方法(带block),由于JCAutoInvalidateTimerTarget
对象没有引用视图控制器,也就无法知晓视图控制器的生命周期,所以需要手动调用NSTimer
对象的invalidate
方法
- (void)addJCTimer
{
self.timer = [JCAutoInvalidateTimer scheduledTimerWithTimeInterval:1 block:^(id obj) {
NSLog(@"logInfo %@", obj);
} userInfo:@"JCTimer" repeats:YES];
}
- (void)dealloc
{
[_timer invalidate];
NSLog(@"dealloc");
}
源码
@interface JCAutoInvalidateTimer : NSObject
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
target:(id)aTarget
selector:(SEL)aSelector
userInfo:(nullable id)userInfo
repeats:(BOOL)yesOrNo;
/**
需要在合适的时间和地点调用NSTimer对象的invalidate方法
*/
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
block:(void (^)(id))block
userInfo:(nullable id)userInfo
repeats:(BOOL)yesOrNo;
@end
#import "JCAutoInvalidateTimer.h"
#pragma mark - JCAutoInvalidateTimerTarget
@interface JCAutoInvalidateTimerTarget : NSObject
@property(nonatomic, weak) id target;
@property(nonatomic, assign) SEL selector;
@property(nonatomic, weak) NSTimer *timer;
@end
@implementation JCAutoInvalidateTimerTarget
- (void)fire:(NSTimer *)timer
{
if (self.target) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self.target performSelector:self.selector withObject:timer.userInfo];
#pragma clang diagnostic pop
} else {
[self.timer invalidate];
}
}
@end
#pragma mark - JCAutoInvalidateTimer
@implementation JCAutoInvalidateTimer
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
target:(id)aTarget
selector:(SEL)aSelector
userInfo:(nullable id)userInfo
repeats:(BOOL)yesOrNo
{
JCAutoInvalidateTimerTarget *timerTarget = [JCAutoInvalidateTimerTarget new];
timerTarget.target = aTarget;
timerTarget.selector = aSelector;
timerTarget.timer = [NSTimer scheduledTimerWithTimeInterval:ti
target:timerTarget
selector:@selector(fire:)
userInfo:userInfo
repeats:yesOrNo];
return timerTarget.timer;
}
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
block:(void (^)(id))block
userInfo:(nullable id)userInfo
repeats:(BOOL)yesOrNo
{
NSMutableArray *info = [NSMutableArray arrayWithObject:[block copy]];
if (userInfo) {
[info addObject:userInfo];
}
return [self scheduledTimerWithTimeInterval:ti
target:self
selector:@selector(blockInvoke:)
userInfo:[info copy] repeats:yesOrNo];
}
+ (void)blockInvoke:(NSArray *)objects
{
void (^block) (id);
block = objects.firstObject;
//userInfo为nil的检查
id info = nil;
if (objects.count == 2) {
info = objects.lastObject;
}
if (block) {
block(info);
} else {
}
}
@end
网友评论