关于NSTimer的问题并保留 [英] Question about NSTimer and retain

查看:120
本文介绍了关于NSTimer的问题并保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码效果很好

@property (nonatomic, retain) NSTimer *timer;
self.timer = [[NSTimer timerWithTimeInterval:kAdsAppearTimeInterval target:self selector:@selector(timerFired:) userInfo:nil repeats:NO] retain];

此代码获得CFRelease。但为什么?我使用retain属性

this code get CFRelease . But why? i use retain property

self.timer = [NSTimer timerWithTimeInterval:kAdsAppearTimeInterval target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];


推荐答案

不是很多......但是:

Not a lot to go on... but:

@property (nonatomic, retain) NSTimer *timer;
self.timer = [[NSTimer timerWithTimeInterval:kAdsAppearTimeInterval target:self selector:@selector(timerFired:) userInfo:nil repeats:NO] retain];

这将最终保留计时器3次并自我保护一次。

That'll end up retaining the timer 3 times and self once.


  1. 定时器+1 for -retain

  2. 定时器+1用于安排它

  3. 属性赋值的计时器+1

  1. Timer +1 for -retain
  2. Timer +1 for scheduling it
  3. Timer +1 for the property assignment

self +1作为计时器的目标

self +1 for being the target of the timer

计时器将在被触发时释放一次(因为它将从运行循环中取消计划)。当计时器失效或被释放时, self 将被释放(你不必关心)。

The timer will be released once when fired (because it'll be unscheduled from the run loop). self will be released when the timer is invalidated or released (you shouldn't have to care).

所以,你有两个保留计数。上面代码中对保留的调用是噪音;不要打扰,因为财产分配将保留它。

So, you have two retain counts to account for. The call to retain in the code above is noise; don't bother as the property assignment will retain it.

这使得财产保留。最明显的方法是在-dealloc中释放计时器。

That leaves the property's retain. The most obvious way is to release the timer in -dealloc.

但是,除非你需要在计时器触发之前使计时器失效,否则没有理由拥有一个实例根据计时器的变量。即使你有iVar,只要你在 timerFired:方法中设置self.timer = nil,就没有理由保留计时器 em>(如果你在任何地方无效,将其设置为nil。)

However, unless you need to potentially invalidate the timer before it fires, there is no reason to have an instance variable referring to the timer at all. Even if you do have an iVar, there is no reason to retain the timer either as long as you set self.timer = nil in your timerFired: method (and set it to nil if you invalidate anywhere).

这篇关于关于NSTimer的问题并保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆