iPhone - NSTimer not repeating after fire

2019-04-05 05:20发布

I am creating and firing a NSTimer with:

ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                           target:self
                                         selector:@selector(handleTimer:)
                                         userInfo:nil
                                          repeats:YES];
[ncTimer fire];

AND

- (void)handleTimer:(NSTimer *)chkTimer {
    // do stuff
}

I am retaining my timer with:

@property (nonatomic, retain) NSTimer *ncTimer;

For some reason the timer is not repeating. It is firing once only and than never again.

5条回答
祖国的老花朵
2楼-- · 2019-04-05 05:34

Assigning to ncTimer as you have will not initiate the properties retain functionality.

Assuming the declaration is within the member object you will need to do:

self.ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES]
查看更多
forever°为你锁心
3楼-- · 2019-04-05 05:47

You can't just assign to the timer that you have put as a property in your header. This should work:

self.ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self selector:@selector(handleTimer:) userInfo:nil repeats: YES];

Also: The fire method fires the timer, out of cycle. If the timer is non repeating it is invalidated. After the line that says fire, add this:


BOOL timerState = [ncTimer isValid];
NSLog(@"Timer Validity is: %@", timerState?@"YES":@"NO");
查看更多
爷的心禁止访问
4楼-- · 2019-04-05 05:47

Got it

Adding timer to mainRunLoop made it working

查看更多
Melony?
5楼-- · 2019-04-05 05:49

The -fire: method manually fires it once. For a timer to be started and repeat, you have to add it to a runloop using [[NSRunLoop currentRunLoop] addTimer: forMode:]

查看更多
姐就是有狂的资本
6楼-- · 2019-04-05 05:54

You can also copy your code inside this block, which inserts the creation of the Timer in the main thread.

The code will therefore remain:

dispatch_async(dispatch_get_main_queue(), ^{
  self.ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                 target:self selector:@selector(handleTimer:) userInfo:nil repeats: YES];
});
查看更多
登录 后发表回答