关于NSTimer的使用和内存释放

-使用攻略

//初始化(参照上边初始化方法)
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerClick:) userInfo:nil repeats:YES];

// 启动定时器 
[timer setFireDate:[NSDate distantPast]];   

//停止定时器 
[timer setFireDate: [NSDate distantFuture]];

//释放
-(void)dealloc{
    if(timer != nil){
        [timer invalidate];
    }
}

-主要初始化方法

// 创建一个定时器,但是没有有添加到运行循环,我们需要在创建定时器后手动的调用 NSRunLoop 对象的 addTimer:forMode: 方法。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

// 创建一个timer并把它指定到一个默认的runloop模式中,并且在 TimeInterval时间后 启动定时器
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;   

// 创建一个定时器,但是么有添加到运行循环,我们需要在创建定时器后手动的调用 NSRunLoop 对象的 addTimer:forMode: 方法。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

// 创建一个timer并把它指定到一个默认的runloop模式中,并且在 TimeInterval时间后 启动定时器
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

// 默认的初始化方法,(创建定时器后,手动添加到 运行循环,并且手动触发才会启动定时器)
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(nullable id)ui repeats:(BOOL)rep NS_DESIGNATED_INITIALIZER;

-主要属性

//管理定时器的启动与停止
@property (copy) NSDate *fireDate;
//管理定时器间隔时间
@property (readonly) NSTimeInterval timeInterval;
// 设置误差范围(7.0新增)
@property NSTimeInterval tolerance NS_AVAILABLE(10_9, 7_0);
//设置定时器是否有效
@property (readonly, getter=isValid) BOOL valid;
//传递参数
@property (nullable, readonly, retain) id userInfo;

-注意事项
1.NSTimer在使用时添加倒runloop中导致不能释放

__weak typeof(self) weakSelf = self;
        timer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:weakSelf selector:@selector(timerClicked:) userInfo:nil repeats:YES];

2.在视图滚动的时候导致定时事件停止

[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值