1

I'm testing NSTimer with OC and Swift. When I write with OC, here is something I don't quite understand: is it REQUIRED to add the timer to the NSRunLoop after the timer is inited? If not required, why can't it be invoked in a loop even if I set the repeats to YES?

Here is my code, I just init a timer and set repeats to YES, and what I expect is the code timerTick: should be invoked every 2 seconds, but it doesn't work as I expect... until I add the timer to the NSRunLoop.

OC:

-(void)viewDidLoad {
    [super viewDidLoad];
     NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];

}

-(void) timerTick:(NSTimer*) timer{
    NSLog(@"ticked,%@",@"aa");
}

I rewrote the same code with Swift As you can see, I don't add the timer to NSRunLoop, however it works as I expected: the runTimeCode method is invoked every 2 seconds.

var timer:NSTimer!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "runTimeCode", userInfo: nil, repeats: true)
     }

    func runTimeCode(){
        NSLog("ticked")
    }

My Question

  1. Is there any bug in OC with iOS9.2 of NSTimer? I searched a lot with Google, but I didn't find anything saying it is REQUIRED if you want to let the timer works correctly. How do I use NSTimer?

  2. Is NSTimer usage different between OC and Swift?

Pang
  • 9,564
  • 146
  • 81
  • 122
xianlong
  • 19
  • 1

2 Answers2

2

First of all, you are using different methods. How come you would get the same result? scheduledTimerWithTimeInterval will automatically add to the NSRunLoop after initializing it. However, timerWithTimeInterval won't. You will need to manually call fire or add it to the NSRunLoop in order to trigger it.

Just like the methods' name mean, scheduledTimerWithTimeInterval will do scheduling for you. As for timerWithTimeInterval, it just gives you a timer. Apple is pretty restricted on the names. Sometimes, you can guess its purpose based on it.

Lucas Huang
  • 3,998
  • 3
  • 20
  • 29
0

With Objective-C, you should try this method :

NSTimer *timer = [NSTimer scheduleTimerWithTimeInterval:2 target:self userinfo:...];

You can see all method's content in Xcode.

Lucas Huang
  • 3,998
  • 3
  • 20
  • 29
JJ.Yuan
  • 63
  • 12