如何知道什么时候失效的`NSTimer`(How to know when to invalidat

2019-07-18 15:05发布

这是我的问题:

我有有一个模型类NSTimer它,我希望定时器为模型对象的整个生命周期中运行。 Initiliazation很简单:我只是在下面一行代码init方法:

self.maintainConnectionTimer = 
             [NSTimer scheduledTimerWithTimeInterval:1 
                                              target:self 
                                            selector:@selector(maintainConnection) 
                                            userInfo:nil 
                                             repeats:YES];

不过,我的问题是, 我怎么否定这一计时器,当模型从内存中释放? 现在,这通常会是容易的,但是,据我所知,则在计划NSTimer操作系统保持着强劲的指针Timer对象。

我应该如何处理呢? 是否有一个模型从内存中释放之前的权利被调用的方法?

Answer 1:

[NSTimer scheduledTimerWithTimeInterval:...] 保留了目标 ,所以如果目标是自己 ,那么你的模型类的实例将永远不会被释放。

作为一种变通方法,可以使用一个单独的对象(称为TimerTarget在下面的示例中)。 TimerTarget引用ModelClass ,以避免保留周期。

这种“辅助类”看起来是这样的。 它的唯一目的是计时器事件转发到“真正的目标”。

@interface TimerTarget : NSObject
@property(weak, nonatomic) id realTarget;
@end

@implementation TimerTarget

- (void)timerFired:(NSTimer*)theTimer
{
    [self.realTarget performSelector:@selector(timerFired:) withObject:theTimer];
}

@end

现在,在你的模型类,你可以创建一个定时器和无效它dealloc

@interface ModelClass ()
@property(strong, nonatomic) NSTimer *timer;
@end

@implementation ModelClass

- (id)init
{
    self = [super init];
    if (self) {
        TimerTarget *timerTarget = [[TimerTarget alloc] init];
        timerTarget.realTarget = self;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                 target:timerTarget
                                               selector:@selector(timerFired:)
                                               userInfo:nil repeats:YES];
    }
    return self;
}

- (void)dealloc
{
    [self.timer invalidate]; // This releases the TimerTarget as well!
    NSLog(@"ModelClass dealloc");
}

- (void)timerFired:(NSTimer*)theTimer
{
    NSLog(@"Timer fired");
}

@end

因此,我们有

modelInstance ===> timer ===> timerTarget ---> modelInstance
(===> : strong reference, ---> : weak reference)

请注意,有来自计时器到模型类的实例没有(强)引用了。

我已用下面的代码,它创建的实例测试这ModelClass和5秒后释放它:

__block ModelClass *modelInstance = [[ModelClass alloc] init];
int64_t delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    modelInstance = nil;
});

输出:

2013-01-23 23:54:11.483 timertest[16576:c07] Timer fired
2013-01-23 23:54:12.483 timertest[16576:c07] Timer fired
2013-01-23 23:54:13.483 timertest[16576:c07] Timer fired
2013-01-23 23:54:14.483 timertest[16576:c07] Timer fired
2013-01-23 23:54:15.483 timertest[16576:c07] Timer fired
2013-01-23 23:54:15.484 timertest[16576:c07] ModelClass dealloc


Answer 2:

基于@马丁 - [R想法,我创建使用哪个更容易,并添加一些检查,以避免崩溃的自定义类。

@interface EATimerTarget : NSObject

// Initialize with block to avoid missing call back
- (instancetype)initWithRealTarget:(id)realTarget timerBlock:(void(^)(NSTimer *))block;

// For NSTimer @selector() parameter
- (void)timerFired:(NSTimer *)timer;

@end

@interface EATimerTarget ()
@property (weak, nonatomic) id realTarget;
@property (nonatomic, copy) void (^timerBlock)(NSTimer *); // use 'copy' to avoid retain counting
@end

@implementation EATimerTarget

- (instancetype)initWithRealTarget:(id)realTarget timerBlock:(void (^)(NSTimer *))block {
    self = [super init];
    if (self) {
        self.realTarget = realTarget;
        self.timerBlock = block;
    }
    return self;
}

- (void)timerFired:(NSTimer *)timer {
    // Avoid memory leak, timer still run while our real target is dealloc
    if (self.realTarget) {
        self.timerBlock(timer);
    }
    else {
        [timer invalidate];
    }
}

@end

这里是我的示例类

@interface MyClass
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation MyClass

- (id)init
{
    self = [super init];
    if (self) {
         // Using __weak for avoiding retain cycles
         __weak typeof(self) wSelf = self;
    EATimerTarget *timerTarget = [[EATimerTarget alloc] initWithRealTarget:self timerBlock: ^(NSTimer *timer) {
        [wSelf onTimerTick:timer];
    }];
         self.timer = [NSTimer timerWithTimeInterval:1 target:timerTarget selector:@selector(timerFired:) userInfo:nil repeats:YES];
         [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    }
    return self;
}

- (void)dealloc
{
    [self.timer invalidate]; // This releases the EATimerTarget as well! 
    NSLog(@"### MyClass dealloc");
}

- (void)onTimerTick:(NSTimer *)timer {
     // DO YOUR STUFF!
     NSLog(@"### TIMER TICK");
}

@end


文章来源: How to know when to invalidate an `NSTimer`