title: iPhone crash- Message sent to deallocated instance
body: <p>Ok, here is the error I am getting:</p>
  
  <pre><code>    -[CFRunLoopTimer invalidate]: message sent to deallocated instance 0x109b05a0 (gdb)
  </code></pre>
  
  <p>Here is the code causing the crash:</p>
  
  <pre><code>    if (waitingOpponentTimer) {
        [waitingOpponentTimer invalidate]; //&lt;-- Crash/error occurs here
        waitingOpponentTimer = nil;
      }
  </code></pre>
  
  <p>And elsewhere:</p>
  
  <pre><code>    NSTimer* waitingOpponentTimer;
  </code></pre>
  
  <p>And also:</p>
  
  <pre><code>    waitingOpponentTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(waitingOpponentTimeOut)userInfo:nil repeats:NO];
  </code></pre>
  
  <p>There is NO other occurence of waitingOpponentTimer anywhere, only the ones I have shown above. waitingOpponentTimeOut action just sets a few variables and does nothing to timers or to waitingOpponentTimer.</p>
  
  <p>I have tried all the following IF statements to prevent the invalidate statement from being reached:</p>
  
  <pre><code>    if (waitingOpponentTimer) {
      if ([waitingOpponentTimer retainCount] &gt; 0) {
      if (waitingOpponentTimer.isValid) {
      if (waitingOpponentTimer != nil) {
  </code></pre>
  
  <p>But in all cases, it still gets thru the IF statement and then causes the crash with the invalidate statement.</p>
  
  <p>So my question is, why/how is invalidate causing an error when the object isValid and is not nil and it's retainCount is greater than zero?</p>
  
  <p>Is there another way to check this to prevent invalidate from being reached?</p>
  
  <p>I am a complete noob to iphone programming and have spent several hours googling to try and figure this out but cannot figure out what I am doing wrong. Any help and suggestions appreciated!</p>
  
  <p>EDIT:
  Just to clarify, I am using this to manually stop the timer before it runs. I understand that if it runs out, it invalidates itself, which is why I am using the IF statement to check if it has already been invalidated (but it is not working). So I think the timer has already invalidated itself when this crash happens, but how do I check if it is already invalidated?</p>
  
  <p>EDIT:
  Ok I marked the correct answer below. I do not know if there is actually a reason why the code gets by the IF statements when the timer was not retained and has already invalidated itself, but the answer is to always use RETAIN if you are going to use the timer in an IF statement.</p>
  
  <p>Here is related info: <a href="https://stackoverflow.com/questions/603044/is-there-any-reason-to-retain-a-scheduled-nstimer-if-you-dont-need-to-invalidat">Is there any reason to retain a scheduled NSTimer if you don&#39;t need to invalidate it?</a></p>