본문 바로가기
Swift

반복 작업을 할 때

by 루에 2015. 10. 21.
반응형

NSTimer를 사용한다.(자바처럼 쓰레드로 반복할 수 있으나 권장하지 않는 방법이다)

기본적인 반복은 아래와 같은 코드로 작성한다.


1
2
3
4
5
6
7
8
@IBAction func startTimer(sender: AnyObject) {
        let interval : Double = 3
        NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "countdown:", userInfo: nil, repeats: true)
    }
    
    func countdown(timer: NSTimer) {
        print(timer)
    }
cs


다른 예제로, 1분이 지나면 얼럿뷰를 띄우는 코드를 작성해보자.

1
2
3
4
5
6
7
8
9
10
11
12
@IBAction func startTimer(sender: AnyObject) {
        let interval : Double = 60
        NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "countdown:", userInfo: nil, repeats: false)
    }
    
    func countdown(timer: NSTimer) {
        let dialog = UIAlertController(title: "60초 지남", message: "얼럿!!", preferredStyle: UIAlertControllerStyle.Alert)
        let action = UIAlertAction(title: "확인", style: UIAlertActionStyle.Default, handler: nil)
        dialog.addAction(action)
        self.presentViewController(dialog, animated: true, completion: nil)
    }
 
cs


간단하게 적용할 수 있다.

반응형

댓글