Swift Playground中的NSTimer.scheduledTimerWithTimeInterval
发布时间:2020-12-14 05:39:39 所属栏目:百科 来源:网络整理
导读:我在 Swift中使用“NSTimer.scheduledTimerWithTimeInterval”时看到的所有示例都使用“target:self”参数显示,但不幸的是,这在Swift Playgrounds中不起作用. Playground execution failed: EXPR:42:13: error: use of unresolvedidentifier 'self' target:
我在
Swift中使用“NSTimer.scheduledTimerWithTimeInterval”时看到的所有示例都使用“target:self”参数显示,但不幸的是,这在Swift Playgrounds中不起作用.
Playground execution failed: <EXPR>:42:13: error: use of unresolved identifier 'self' target: self, 以上引用的示例导致错误: func printFrom1To1000() { for counter in 0...1000 { var a = counter } } var timer = NSTimer.scheduledTimerWithTimeInterval(0,target: self,selector: Selector("printFrom1To1000"),userInfo: nil,repeats: false ) timer.fire()
这些天你真的不应该使用NSTimer.它消耗了大量资源,导致不必要的电池消耗,而且API会导致丑陋的代码.
使用dispatch_after()代替: dispatch_after(0,dispatch_get_main_queue()) { () -> Void in for counter in 0...1000 { var b = counter } } 当然,由于计时器会在游乐场运行后触发,你需要等效的timer.fire()来强制代码立即执行,而不是在0秒延迟之后执行.这是如何工作的: let printFrom1To1000 = { () -> Void in for counter in 0...1000 { var b = counter } } dispatch_after(0,dispatch_get_main_queue(),printFrom1To1000) printFrom1To1000() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |