NSTimer 销毁问题 和 iOS中控制器的释放问题

俗话说的好,前人栽树后人乘凉,最近看了很多博文,不少博文提到了NSTimer的销毁问题, 之前我都没怎么注意,现在对照着文章一一实践发现坑还真不少。下面是我读到的几篇博文分享给大家

@啸笑天的NSTimer
@庞海礁的个人空间
@汪海的实验室「iOS 中的 NSTimer」

这几篇文章阐述了NSTimer的销毁问题,并且都给出解决方案

这里就提供一个简洁的方案,是由啸笑天提供的

+ (NSTimer *)ez_scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats
{
    void (^block)() = [inBlock copy];
    NSTimer * timer = [self scheduledTimerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats];
    return timer;
}

+ (NSTimer *)ez_timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats
{
    void (^block)() = [inBlock copy];
    NSTimer * timer = [self timerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats];
    return timer;
}

+ (void)__executeTimerBlock:(NSTimer *)inTimer;
{
    if([inTimer userInfo])
    {
        void (^block)() = (void (^)())[inTimer userInfo];
        block();
    }
}

啸笑天解决方案的github地址

https://github.com/easyui/EZToolKit/blob/master/EZToolKit/EZCategory/NSTimer%2BEZ_Helper.m

提醒

上面的解决办法,只是解决了target的强引用问题,但是NSTimer销毁还是得自己在使用的viewController的dealloc方法中销毁

- (void)dealloc {
    if ([self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

或者你有更好的办法,请拼命的@我

NSTimer的创建方式

创建方式有2种

1.这种创建方式,会主动添加到主循环中,即默认会执行,但当用户按住其他控件的时候,它就会停止执行,当放开控件,它才继续执行

__weak typeof(self) weakSelf = self;
self.timer = [NSTimer ez_scheduledTimerWithTimeInterval:1.f block:^{
    NSLog(@"nextPage");
    [weakSelf nextPage];
} repeats:YES];

2.这种创建方式,不会主动添加到主循环中,得手动添加,有两种执行模式

NSRunLoopCommonModes 按住其它控件,不会停止执行
NSDefaultRunLoopMode 按住其它控件,会停止执行,和第一种方式一样
self.timer = [NSTimer ez_timerWithTimeInterval:1.f block:^{
    NSLog(@"nextPage");
    [weakSelf nextPage];
} repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
原文地址:https://www.cnblogs.com/Jenaral/p/5945755.html