ios定时器使用的几点优化

1. 将定时器添加到runloop中,一般在viewWillAppear方法中添加

timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(dealTimer) userInfo:nil repeats:YES];

        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];


2.将计数器的repeats设置为Yes的时候,self的引用计数会加1.因此可能会导致self(即viewController)不能release,所以,必须在viewDisappear的时候,将计数器timer停止,否则可能会导致内存泄漏。

- (void)viewDidDisappear:(BOOL)animated {

 [timer invalidate];

timer = nil;

}

3.当程序退出到后台时,应当暂停定时器,当再次进入前台时再次开启定时器.避免定时器在不必要的时候一直运行,占用cpu

在viewDidLoad方法中响应系统通知:

[[NSNotificationCenter defaultCenteraddObserver:selfselector:@selector(enterActive:) name:UIApplicationDidBecomeActiveNotification object:nil];

    [[NSNotificationCenter defaultCenteraddObserver:selfselector:@selector(enterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];


实现通知方法:

- (void)enterActive:(NSNotification*)noti{

// 程序进入前台,开启定时器

[timer setFireDate:[NSDate distantPast]];

}


- (void)enterBackground:(NSNotification *)noti {

// 程序进入后台,关闭定时器

[timer  setFireDate:[NSDate distantFuture]];

}







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值