title: Retaining repeating NSTimer for later access?
body: <p>I am creating an NSTimer in the <code>createTimer</code> method that I want to refer back to in the later <code>cancelTimer</code> method. To facilitate this I am taking ownership of the NSTimer via a retained property so that I can refer back to it later. The issue that is confusing me is, if I start the timer, cancel it and start it again the code crashes.</p>
  
  <pre><code>@property(nonatomic, retain) NSTimer *walkTimer;
  </code></pre>
  
  <p>.</p>
  
  <pre><code>-(void)createTimer {
      NSTimer *tempTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimerDisplay) userInfo:nil repeats:YES];
      [self setWalkTimer:tempTimer];
  }
  
  -(void)cancelTimer {
      [walkTimer release];
      [[self walkTimer] invalidate];
  }
  </code></pre>
  
  <p>Now I seem to have fixed this by changing cancelTimer to:</p>
  
  <pre><code>-(void)cancelTimer {
      [self setWalkTimer:nil];
      [[self walkTimer] invalidate];
  }
  </code></pre>
  
  <p>I am just curious why release was not working, my understanding was that:</p>
  
  <ol>
  <li>NSTimer (Autorelease object, not owned by me)</li>
  <li>setWalkTimer (takes ownership for me, retainCount+1)</li>
  <li>release (relinquishes my ownership, retainCount-1)</li>
  <li>invalidate (lets system dispose of timer)</li>
  </ol>
  
  <p><strong>EDIT:</strong></p>
  
  <pre><code>// this fails ...
  -(void)cancelTimer {
      [[self walkTimer] invalidate];
      [walkTimer release];
  }
  
  // this works fine ...
  -(void)cancelTimer {
      [[self walkTimer] invalidate];
      [self setWalkTimer: nil];
  }
  </code></pre>
  
  <p><strong>EDIT: 002</strong></p>
  
  <p>Initially I think I was mixing up </p>
  
  <pre><code>@property(nonatomic, retain) NSTimer *walkTimer;
  // &amp;
  [self setWalkTimer];
  </code></pre>
  
  <p>and thinking that I needed a release to balance the property, I don't I either overwrite it with a new set (either to another object or nil) and finally release the property in dealloc.</p>
  
  <p>Is the property(retain) the same as retain, I would say no, which is where I was going wrong I think.</p>
  
  <p><strong>EDIT: 003</strong>
  With regards to this question I think I personally confused things by wrongly using <code>[walkTimer release]</code> As a result the topic drifted to essentially a new question which I have written up as <a href="https://stackoverflow.com/questions/4945028/repeating-nstimer-weak-reference-owning-reference-or-ivar">this</a></p>