目标 C:计时器第二次打开时导致应用程序崩溃
我在头文件中声明了 NSTimer。当点击播放
按钮时,它会打开计时器。下一步点击将禁用计时器。第三次点击会使应用程序崩溃,并且没有错误消息。为什么会发生这种情况呢?
-(IBAction) play {
if ([col1 isValid]) {
[col1 invalidate];
} else {
col1 = [NSTimer scheduledTimerWithTimeInterval:.8 target:self selector:@selector(playCol1) userInfo:nil repeats:YES];
}
I have my NSTimer declared in the header file. When the play
button is tapped, it turns on the timer. Next tap disables timer. A third tap crashes the app with no error message. Why would this be happening?
-(IBAction) play {
if ([col1 isValid]) {
[col1 invalidate];
} else {
col1 = [NSTimer scheduledTimerWithTimeInterval:.8 target:self selector:@selector(playCol1) userInfo:nil repeats:YES];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
invalidate
将导致对象被释放。因此,您尝试在错误引用上调用isValid
。在使col1
对象无效后,将其清空,应该没问题。invalidate
will cause the object to be released. So, you are attempting to callisValid
on a bad reference. nil out thecol1
object after you invalidate it, and you should be fine.崩溃是因为它试图使已经失效的计时器
col1
失效。您是否尝试过
[col1 isValid]==YES
?尝试一下,如果这不起作用,请尝试使用自定义的整数或布尔类型标志。
我在
isValid
方法上遇到了类似的问题,并通过使用 BOOL 类型的标志来解决它,希望这对您有帮助。
自定义标志的使用示例:
Crash is because it is trying to
invalidate
an already invalidated timercol1
.Did you try
[col1 isValid]==YES
?Try out that and if that doesn't work then try using an custom
integer
orBOOL
type flag.I had a similar problem with the
isValid
Method and made a workaround for it by using flag of BOOL typeHope this helps you.
SAMPLE OF USAGE OF CUSTOM FLAGS: