Iphone 如何阻止我不知道的NSTimer';我不知道他是否被释放了

Iphone 如何阻止我不知道的NSTimer';我不知道他是否被释放了,iphone,xcode,crash,nstimer,Iphone,Xcode,Crash,Nstimer,很抱歉问这个问题,但现在是第三天,我试图解决这个问题,但到目前为止没有任何进展 问题在于:在游戏中,在用户回答一个问题和下一个问题之间有一个停顿。在其他一些情况下,游戏中也会出现这种暂停。为此,我使用了一个NSTimer 在.h中,我有: @property(nonatomic,retain) NSTimer *scheduleTimer; 在.m @synthesize scheduleTimer; scheduleTimer = [NSTimer scheduledTimerWithTi

很抱歉问这个问题,但现在是第三天,我试图解决这个问题,但到目前为止没有任何进展

问题在于:在游戏中,在用户回答一个问题和下一个问题之间有一个停顿。在其他一些情况下,游戏中也会出现这种暂停。为此,我使用了一个NSTimer

在.h中,我有:

@property(nonatomic,retain) NSTimer *scheduleTimer;
在.m

@synthesize scheduleTimer;

scheduleTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector: @selector(playFeedbackSound) userInfo: nil repeats: NO];
现在这个工作很好。但是当用户退出ViewController时,我需要使计时器无效。否则计时器将启动,然后应用程序崩溃或弹出不属于其他视图的内容等

因此,我写:

- (void)viewWillDisappear:(BOOL)animated {
    [scheduleTimer invalidate];   
}
现在,如果实际设置了计时器,那么这就完成了任务。但如果没有这样的计时器,应用程序就会崩溃

我尝试了可能所有的东西,包括@try(它也会使应用程序崩溃,僵尸说“*-[CFRunLoopTimer invalidate]:发送到解除分配实例0x567640的消息”)。由于计时器在完成后被释放,[scheduleTimer isValid]也会使应用程序崩溃

现在我已经非常绝望了,作为最后的手段,我正在考虑用UIView animateWithDuration替换计时器,它的持续时间不可见


然而,我认为这应该是一个相当标准的情况。我只是不知道为什么我找不到这个显而易见的任务的答案。你能帮忙吗?谢谢

我认为问题在于,
NSTimer
在您使其失效之前会自动删除

所以你应该:

scheduleTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector: @selector(playFeedbackSound) userInfo: nil repeats: NO] retain];
您还应该
释放
视图中的计时器将消失:

[scheduleTimer release];
但更好的解决方案可能是使用dot属性语法来处理retain/release:

self.scheduleTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector: @selector(playFeedbackSound) userInfo: nil repeats: NO];
然后:

- (void)viewWillDisappear:(BOOL)animated {
    if (self.scheduleTimer != nil) {
        [self.scheduleTimer invalidate];
        self.scheduleTimer = nil;
    }
}

创建一个方法使计时器无效,该计时器还将属性设置为nil:

- (void) invalidateTimer
{
    if (self.scheduleTimer) {
       [self.scheduleTimer invalidate];   
       self.scheduleTimer = nil;  
    }
}
。。。然后在使计时器无效时调用该方法。例如:

- (void)viewWillDisappear:(BOOL)animated 
{
   [super viewWillDisappear: animated];
   [self invalidateTimer];
}
使用以下方法确保计时器保持不变:


self.scheduleTimer=[NSTimer scheduledTimerWithTimeInterval:1.0目标:自选择器:@selector(playFeedbackSound)用户信息:无重复:否]

***-[CFRunLoopTimer invalidate]:发送到解除分配实例0x5365CE0的消息似乎通过了测试,然后运行到invalidate。所以不是零,但是。。。这是什么?那么我认为真正的问题是,当按原样分配计时器时,您没有使用
self.scheduleTimer=
将返回一个自动释放的NSTimer
self.scheduleTimer=
将保留计时器,这样它就不会是自动释放的Duuuuuuhhhhhhh Mattias,完全保留了它!:-)非常感谢。你能给我指一份文件,详细解释一下self的用法吗?值得注意的是,在设置属性时没有使用点符号。尽管这之前可能没有发生过,但这意味着您的计时器可能会在实际启动或失效之前被销毁,特别是在内存不足的情况下。不幸的是,NSTimer会自动释放,我不知道ViewController如何成为NSTimer的委托,因此我可以将其设置为nil。然而,感谢您提供的代码示例,我还忘了放置[super ViewWillEnglishe:animated];:-oSuper调用应在invalidate调用之后执行。拆卸超级调用总是在末尾出现,设置超级调用总是在开头出现。