Question about NSTimer and retain

后端 未结 2 1983
故里飘歌
故里飘歌 2020-12-22 10:20

This code works well

@property (nonatomic, retain) NSTimer *timer;
self.timer = [[NSTimer timerWithTimeInterval:kAdsAppearTimeInterval target:self selector:@         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 10:53

    For a non-repeating timer, if you need a reference to the instance variable, I would not recommend a retain property in its declaration to avoid confusion.

    setting the instance variable (myTimer)

     myTimer = [NSTimer scheduledTimerWithTimeInterval:myTimerInterval
                                                target:self
                                              selector:@selector(myTimerFired:)
                                              userInfo:nil
                                               repeats:NO];
    

    when the timer fires, you can mark the instance variable as nil since its released when the timer is fired

    - (void) myTimerFired: (NSTimer *) theTimer{
    
                myTimer = nil;
            //etc
        }
    

    This way if you have to reference your instance variable (for example to disable the timer when exiting a View controller)

     -(void) onBack {
                 if(myTimer){
                     [myTimer invalidate];
                     myTimer = nil;
                  }
        }
    

提交回复
热议问题