うちのいぬ Tech Blog

Tech Blog of Uchinoinu/My dog

How to execute some methods at regular intervals like clock

Call

NSTimer.scheduledTimerWithTimeInterval(
            1, // second
            target: self,
            selector: #selector(ThisClass.methodName),
            userInfo: nil,
            repeats: true
        )

Execute

func methodName() {
        print("pikachu!")
}

In UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()

        updateDateLabel()
        NSTimer.scheduledTimerWithTimeInterval(
            1,
            target: self,
            selector: #selector(ThisViewController.updateClock),
            userInfo: nil,
            repeats: true
        )
    }

    func updateClock() {
        datetimeLabel.text = Util.stringFromNSDate(NSDate(), format: ""yyyy-MM-dd HH:mm:ss"")
    }

Result

f:id:susanne:20160804211908g:plain