别忘了NSTimer会保留其目标对象

[NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)
                                     target:(nonnull id)
                                   selector:(nonnull SEL)
                                   userInfo:(nullable id)
                                    repeats:(BOOL)];

此方法会创建计时器,并将其预先安排在当前运行循环中,会在指定的时间间隔执行任务。

由于计时器会保留其目标对象,所以反复执行任务通常会导致应用程序出问题。

#import "EOCClass.h"

@implementation EOCClass
{
    NSTimer *_pollingTimer;
}

-(instancetype)init
{
    return [super init];
}

-(void)dealloc
{
    [_pollingTimer invalidate];
}

-(void)p_doPoll
{
    
}

-(void)startPolling
{
    _pollingTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
                                                     target:self
                                                   selector:@selector(p_doPoll)
                                                   userInfo:nil
                                                    repeats:YES];
}

-(void)stopPolling
{
    [_pollingTimer invalidate];
    _pollingTimer = nil;
}

@end

这样写就会有问题,因为实例保存了计时器,计时器又保存了实例。外界对象在释放最后一个指向本实例的引用之前,必须先调用stopPolling方法。

用块可以解决这个问题:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSTimer (EOCBlocksSupport)

typedef void(^EOCBlock)(void);

+(NSTimer *)eoc_scheduledTimerWithInterval:(NSTimeInterval)interval
                                     block:(EOCBlock)block
                                   repeats:(BOOL)repeats;

@end

NS_ASSUME_NONNULL_END
#import "NSTimer+EOCBlocksSupport.h"

@implementation NSTimer (EOCBlocksSupport)

+(void)eoc_blockInvoke:(NSTimer *)timer
{
    EOCBlock block = timer.userInfo;
    if (block)
    {
        block();
    }
}

+(NSTimer *)eoc_scheduledTimerWithInterval:(NSTimeInterval)interval
                                     block:(EOCBlock)block
                                   repeats:(BOOL)repeats
{
    return [self scheduledTimerWithTimeInterval:interval
                                         target:self
                                       selector:@selector(eoc_blockInvoke:)
                                       userInfo:[block copy]
                                        repeats:repeats];
}

@end
-(void)startPolling
{
    __weak EOCClass *weakSelf = self;
    _pollingTimer = [NSTimer eoc_scheduledTimerWithInterval:5.0
                                                      block:^
    {
        EOCClass *strongSelf = weakSelf;
        [strongSelf p_doPoll];
    }
                                                    repeats:YES];
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Win_77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值