매분 함수를 어떻게 실행할 수 있습니까? JavaScript에서 같은 setInterval
일을 할 수 있습니다. Swift에 비슷한 것이 있습니까?
원하는 출력 :
1 분에 한 번씩 Hello World …
답변
var helloWorldTimer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: Selector("sayHello"), userInfo: nil, repeats: true)
func sayHello()
{
NSLog("hello World")
}
Foundation을 가져 오는 것을 잊지 마십시오.
스위프트 4 :
var helloWorldTimer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(ViewController.sayHello), userInfo: nil, repeats: true)
@objc func sayHello()
{
NSLog("hello World")
}
답변
iOS 버전 10 이상을 대상으로하는 경우 Timer
잠재적 인 강력한 참조주기를 단순화하는 의 블록 기반 변환을 사용할 수 있습니다. 예 :
weak var timer: Timer?
func startTimer() {
timer?.invalidate() // just in case you had existing `Timer`, `invalidate` it before we lose our reference to it
timer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] _ in
// do something here
}
}
func stopTimer() {
timer?.invalidate()
}
// if appropriate, make sure to stop your timer in `deinit`
deinit {
stopTimer()
}
하지만 Timer
완전성을 위해서, 일반적으로 최고입니다, 당신은 또한 배경 스레드에 예약 타이머에 유용 파견 타이머를 사용할 수 있음을 유의하십시오. 파견 타이머로,있는 거 블록 기반, 그것은 이전과 강한 참조주기 문제의 일부 방지 그들은 이후 target
/의 selector
패턴을 Timer
오래 사용으로, weak
참조.
그래서:
var timer: DispatchSourceTimer?
func startTimer() {
let queue = DispatchQueue(label: "com.domain.app.timer") // you can also use `DispatchQueue.main`, if you want
timer = DispatchSource.makeTimerSource(queue: queue)
timer!.schedule(deadline: .now(), repeating: .seconds(60))
timer!.setEventHandler { [weak self] in
// do whatever you want here
}
timer!.resume()
}
func stopTimer() {
timer?.cancel()
timer = nil
}
deinit {
self.stopTimer()
}
자세한 내용 은 Concurrency Programming Guide 의 Dispatch Sources 섹션에있는 Dispatch Source Examples 의 Creating a Timer 섹션을 참조하십시오.
Swift 2 의 경우이 답변의 이전 개정판을 참조하십시오 .
답변
다음 은 명명 된 함수가 아닌 클로저를 사용하는 NSTimer
Swift 3 ( NSTimer
으로 이름이 변경됨 Timer
) 에 대한 답변에 대한 업데이트입니다 .
var timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) {
(_) in
print("Hello world")
}
답변
약간의 시간 드리프트를 허용 할 수 있다면 매분 코드를 실행하는 간단한 솔루션이 있습니다.
private func executeRepeatedly() {
// put your code here
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { [weak self] in
self?.executeRepeatedly()
}
}
executeRepeatedly()
한 번만 실행 하면 1 분마다 실행됩니다. 소유 개체 ( self
)가 해제 되면 실행이 중지됩니다 . 플래그를 사용하여 실행을 중지해야 함을 나타낼 수도 있습니다.
답변
사용할 수 있습니다 Timer
(스위프트 3)
var timer = Timer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector("function"), userInfo: nil, repeats: true)
selector ()에서 함수 이름을 입력합니다.
답변
신속한 3.0에서 GCD는 리팩토링되었습니다.
let timer : DispatchSourceTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
timer.scheduleRepeating(deadline: .now(), interval: .seconds(60))
timer.setEventHandler
{
NSLog("Hello World")
}
timer.resume()
이것은 특정 큐를 디스패치해야 할 때 특히 유용합니다. 또한 사용자 인터페이스 업데이트에 이것을 사용할 계획이라면 CADisplayLink
GPU 새로 고침 빈도와 동기화되어 있는지 살펴 보는 것이 좋습니다 .
답변
