[swift] Swift에서의 타이머와 디스패치 타이머 활용하기

이번에는 Swift에서 타이머와 디스패치 타이머를 어떻게 사용하는지 알아보겠습니다.

타이머(Timer)와는 무엇인가요?

타이머(Timer) 는 코드 내에서 특정 작업을 주기적으로 실행하기 위해 사용됩니다. 예를 들어, 주기적으로 UI를 업데이트하거나 백그라운드 작업을 실행하는 등의 경우에 유용하게 사용됩니다.

Swift에서는 Timer 클래스를 사용하여 타이머를 생성하고 관리할 수 있습니다.

타이머 사용하기

아래는 간단한 예제 코드입니다. 매 초마다 현재 시간을 콘솔에 출력하는 타이머를 설정하는 방법을 보여줍니다.

import Foundation

class TimerExample {
    var timer: Timer?

    init() {
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }

    @objc func updateTime() {
        let currentTime = Date()
        print("Current time is \(currentTime)")
    }
}

위 예제에서는 Timer.scheduledTimer 메서드를 사용하여 매 초마다 updateTime 메서드를 호출하는 타이머를 생성합니다.

디스패치 타이머(Dispatch Timer) 사용하기

디스패치 타이머(Dispatch Timer)는 GCD(Grand Central Dispatch)를 사용하여 타이머를 관리합니다. 보다 유연하고 정교한 타이머 기능을 제공합니다.

아래는 디스패치 타이머를 사용하여 위와 동일한 작업을 하는 예제 코드입니다.

import Dispatch

class DispatchTimerExample {
    var timer: DispatchSourceTimer?

    init() {
        timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        timer?.schedule(deadline: .now(), repeating: .seconds(1))
        timer?.setEventHandler { [weak self] in
            let currentTime = Date()
            print("Current time is \(currentTime)")
        }
        timer?.resume()
    }
}

결론

Swift에서는 Timer 클래스와 디스패치 타이머를 사용하여 타이머를 생성하고 관리할 수 있습니다. 각각의 방법에 따라 다양한 상황에 맞게 타이머를 활용할 수 있으니, 상황에 맞게 적절한 방법을 선택하여 사용하시면 됩니다.

더 많은 정보는 Apple 공식 문서를 참고하세요.