NSTimer.scheduledTimerWithTimeInterval in Swift Playground

前端 未结 3 898
南方客
南方客 2020-12-20 19:25

All the examples I\'ve seen on using the \"NSTimer.scheduledTimerWithTimeInterval\" within Swift show using the \"target: self\" parameter, but unfortunately this doesn\'t w

3条回答
  •  抹茶落季
    2020-12-20 20:15

    To get this to run directly within a Swift Playground, you need to embed the printFrom1To1000 function within a class and then set an instance of that class to the "target:" parameter instead of using "self".

    Here's a full working example:

    class myClass: NSTimer{
        func printFrom1To1000() {
            for counter in 0...1000 {
                var b = counter
            }
        }
    }
    
    let myClassInstance = myClass()
    
    var timer = NSTimer.scheduledTimerWithTimeInterval(0,
        target: myClassInstance,
        selector: Selector("printFrom1To1000"),
        userInfo: nil,
        repeats: false
    )
    timer.fire()
    

提交回复
热议问题