(Turn) [IOS]Timer timer

From: http://blog.csdn.net/springjustin/article/details/50978671

 

NSTimer

way 1

    // create timer

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(test) userInfo:nil repeats:YES];

 

    // stop the timer

    [timer invalidate];

 

way 2

    // create timer

    NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(test) userInfo:nil repeats:YES];

    // Add the timer to the runloop, otherwise the timer will not start

    [[NSRunLoop mainRunLoop] addTimer: timer forMode: NSRunLoopCommonModes];

 

    // stop the timer

    [timer invalidate];

Mode 1 will automatically add the created timer to the current thread runloop by default, without the need to add it manually. But in this mode, when the screen is scrolled, the runloop will enter another mode, and the timer will be paused. In order to solve this problem, the timer can be added to the NSRunLoopCommonModes mode as in Mode 2.

Method 1 and method 2 will execute the test method after the interval set time (in this example, set to 2s) after setting. If you need to execute it immediately, you can use the following code.

Logout timer: [time fire];

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326020355&siteId=291194637