[英]Objective C: Timer crashes app when turned on a second time
I have my NSTimer declared in the header file. 我在头文件中声明了我的NSTimer。 When the play
button is tapped, it turns on the timer. 轻按play
按钮后,它将打开计时器。 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];
}
invalidate
will cause the object to be released. invalidate
将导致对象被释放。 So, you are attempting to call isValid
on a bad reference. 因此,您试图在错误的引用上调用isValid
。 nil out the col1
object after you invalidate it, and you should be fine. 使col1
对象无效后,将其取消,这应该没问题。
-(IBAction) play {
if ([col1 isValid]) {
[col1 invalidate];
col1 = nil;
} else {
col1 = [NSTimer scheduledTimerWithTimeInterval:.8 target:self selector:@selector(playCol1) userInfo:nil repeats:YES];
}
Crash is because it is trying to invalidate
an already invalidated timer col1
. 崩溃是因为它试图invalidate
已经无效的计时器col1
无效。
Did you try [col1 isValid]==YES
? 您是否尝试过[col1 isValid]==YES
? Try out that and if that doesn't work then try using an custom integer
or BOOL
type flag. 尝试一下,如果不起作用,请尝试使用自定义integer
或BOOL
类型标志。
I had a similar problem with the isValid
Method and made a workaround for it by using flag of BOOL type 我对isValid
方法有类似的问题,并使用BOOL类型的标志对其进行了解决
Hope this helps you. 希望这对您有所帮助。
SAMPLE OF USAGE OF CUSTOM FLAGS: 定制标志的使用示例:
BOOL invalidateTimer = NO;
-(IBAction) play
{
if (invalidateTimer == YES)
{
[col1 invalidate];
}
else if (invalidateTimer == NO)
{
col1 = [NSTimer scheduledTimerWithTimeInterval:.8 target:self selector:@selector(playCol1) userInfo:nil repeats:YES];
invalidateTimer = YES;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.