iOS/Swift

[Swift] Timer 사용방법, 주의사항

코르피 2023. 3. 22. 18:59
반응형

Timer

iOS 2.0 부터 사용가능.

Foundation에 들어있음.

 

타이머를 설정해서 일정 Interval 간격마다 어떤 실행을 할 수 있게 도와주는 라이브러리

 

사용법

인스턴스를 만들 때 클래스 메서드를 사용하는 방법과 인스턴스를 생성하는 방법이 있음.

 

 

사용 예제

레이블 하나와 실행 버튼 하나 생성

 

@IBAction func timerStopFunc(_ sender: UIButton) {
    timerStartButton.isHidden = false
    timerStopButton.isHidden = true

    timer?.invalidate()
    self.timer = nil
}
    
@IBAction func timerStartFunc(_ sender: UIButton) {
    guard timer == nil else { return }

    timerStartButton.isHidden = true
    timerStopButton.isHidden = false

    timer = Timer(timeInterval: 1, repeats: true, block: { timer in
        self.timerLabel.text = "\(Int(self.timerLabel.text!)! + 1)"
    })

    if timer != nil {
        RunLoop.current.add(timer!, forMode: .default)
    }
}

 

 

주의사항 

 

timer가 여러개가 생성되지 않도록 nil 체크를 잘 할 것

반응형

'iOS > Swift' 카테고리의 다른 글

[Swift] 동시성, 병렬성, 동기, 비동기  (1) 2024.02.01
[Memory] heap memory  (0) 2024.02.01
[Trouble] stride(from: to: by:) 와 stride(from: through: by:)  (0) 2023.04.07
[Trouble] protocol get set  (0) 2023.03.28