NSTimer 访问错误
我正在尝试创建一个 NSTimer,然后使其无效并释放它,然后将其设置为新的计时器。但是,当我尝试再次设置计时器成员变量时,我收到 EXC_BAD_ACCESS 。
代码如下:
1) 我设置了计时器成员 var (它被设置为保留)
self.mPageTimer = [NSTimer scheduledTimerWithTimeInterval:kPageTimerInterval target:self selector:@selector(pageTimerCallback) userInfo:nil repeats:NO];
2) 我让它离开
[mPageTimer invalidate];
[mPageTimer release];
当我尝试再次调用步骤 1 中的代码片段时,这会导致崩溃,但我不确定为什么。我通过设置它来保留它,然后释放它,所以不应该处理该对象并且我的成员变量可以设置为新分配的计时器吗?
如果我这样做,它不会崩溃并且工作正常:
[mPageTimer invalidate];
[mPageTimer release];
mPageTimer = nil;
我看不出我在释放对象时做错了什么,因为,无论情况是否如此,我不应该总是能够设置我的成员变量到任何新创建的 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.
Code below:
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) I let it go
[mPageTimer invalidate];
[mPageTimer release];
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;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以安全地假设...
@property
的 setter,而是来自另一种方法 while 你@synthesize mPageTimer
并且@property(非原子,保留)NSTimer* mPageTimer
?(无论是非原子还是原子并不重要)
如果是这种情况,你的崩溃是预料之中的:
所以简而言之:
如果您有计时器属性,提供您自己的设置器并让每次访问都使用它。
(允许两个例外:1. setter 的实现 2. 在 dealloc 中,您
释放
计时器*)(* 不要使您在 dealloc 中作为目标的计时器无效:这绝对毫无意义 !)
Is it safe to assume, that...
@property
, but from another method while you@synthesize mPageTimer
and@property (nonatomic, retain) NSTimer* mPageTimer
?(whether nonatomic or atomic doesn't matter)
If that's the case, your crash is expected:
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*)(* Don't invalidate a timer that you're the target of in dealloc: It is absolutely pointless!)