이제 실제 시계처럼 포어그라운드 상태에서도 시간이 계속 업데이트 되도록 구현해보자.
Class Timer
: 입력한 시간이 경과하면 타겟에 특정 메시지를 보내는 타이머
Type Method scheduledTimer(timeInterval:target:selector:userInfo:repeats:)
: Timer 인스턴스를 생성하고 현재 런루프에 등록한다.
이제 실제 시계로서의 기능을 하려면 매 초마다 시간이 업데이트 되어야 한다.
Timer 클래스의 scheduledTimerwithTimeInterval 메서드를 이용하여 1초마다 updateTime 메서드가 실행되도록 구현해보자.
class ViewController: UIViewController {
...
// 따로 초기값을 지정하지 않으므로 옵셔널 Timer 타입으로 timer 라는 프로퍼티를 선언했다.
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
updateTimeLabel()
// 1초 간격으로 현재의 객체에 updateTimeLabel 메서드를 실행하도록 타이머를 런루프에 등록한다.
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true)
}
// deinit은 인스턴스가 메모리해서 해제 되기 직전에 자동으로 호출되는 메서드이다.
deinit {
if let timer = self.timer {
timer.invalidate() // 등록한 timer를 런루프에서 제거한다.
}
}