NSTimer错误访问 [英] NSTimer bad access
问题描述
我尝试创建一个NSTimer,然后失效并释放它,然后将其设置为一个新的计时器。
I'm trying to create an NSTimer, then invalidate and release it, then set it to a new timer. However, I am getting an EXC_BAD_ACCESS when trying to set the timer member var again.
代码如下:
1)我设置定时器成员var(设置为保留)
1) I set the timer member var (it's set to retain)
self.mPageTimer = [NSTimer scheduledTimerWithTimeInterval:kPageTimerInterval target:self selector:@selector(pageTimerCallback) userInfo:nil repeats:NO];
2)我放开
[mPageTimer invalidate];
[mPageTimer release];
当我尝试再次调用步骤1中的代码段时,会导致崩溃,肯定为什么。我保留它通过设置它,然后我释放它,所以不应该对象被照顾和我的成员var确定设置为一个新的分配的计时器?
This results in the crash when I try to call the snippet in step 1 again, but I am not sure why. I retained it by setting it, and then I release it, so shouldn't the object be taken care of and my member var ok to set to a new allocated timer?
如果我这样做,它不会崩溃,工作正常:
If I do this, it doesn't crash and works fine:
[mPageTimer invalidate];
[mPageTimer release];
mPageTimer = nil;
我看不到我在发布对象时做错了什么,因为,如果是这样,我应该不能总是将我的成员var设置为任何新创建的nstimer,泄漏或不是?
I can't see how I'm doing something wrong with releasing the object, because, regardless of if that were the case, shouldn't I be able to always set my member var to whatever newly created nstimer, leak or not?
推荐答案
可以放心,假设...
Is it safe to assume, that...
- 代码段2)不是 c c 合成mPageTimer 和
- 定时器的声明为
@property(nonatomic,retain)NSTimer * mPageTimer
?
(无论是非原子的还是无关紧要的)
- snippet 2) is not from the setter of the
@property
, but from another method while you - simply
@synthesize mPageTimer
and - the declaration for the timer is
@property (nonatomic, retain) NSTimer* mPageTimer
?
(whether nonatomic or atomic doesn't matter)
如果是这种情况,您的崩溃是预期的:
If that's the case, your crash is expected:
create timer (timer retains you, timer is autoreleased!)
schedule timer (runloop retains the timer)
assignment through setter (you retain the timer)
... (time passes)
has it fired?
Yes:
since your timer is non-recurring, the runloop has marked it
as invalid and released it after invocation of "pageTimerCallback:"
calling "invalidate":
has it fired?
No:
runloop unschedules and releases
Yes:
noop or release (read: "I don't know and admittedly don't care")
calling "release" (you are no longer the owner)
... (time passes)
assignment through synthesized setter:
[newTimer retain];
[oldTimer release]; // Crash due to overrelease!
简而言之:
如果定时器的属性提供您自己的setter并使每个访问都使用。
(允许两个例外:1.在dealloc中实现setter 2.在< c $ c> release 定时器*)
So in short:
If you have a property for a timer, provide your own setter and make every access use it.
(Two exceptions allowed: 1. implementation of the setter 2. in dealloc where you release
the timer*)
(*不要使定时器失效, a href =http://stackoverflow.com/questions/4945028/repeating-nstimer-weak-reference-owning-reference-or-ivar/4946038#4946038>这是绝对的无意义 a>!)
(* Don't invalidate a timer that you're the target of in dealloc: It is absolutely pointless!)
这篇关于NSTimer错误访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!