许多Cocoa和CocoaTouch方法都有完成回调,实现为Objective-C中的块和Swift中的闭包.但是,在Playground中尝试这些时,永远不会调用完成.例如:
// Playground - noun: a place where people can play
import Cocoa
import XCPlayground
let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.currentQueue() {
response, maybeData, error in
// This block never gets called?
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
} else {
println(error.localizedDescription)
}
}
Run Code Online (Sandbox Code Playgroud)
我可以在我的Playground时间轴中看到控制台输出,但是println我的完成块永远不会被调用...
使用Swift 3.0在游乐场工作我有这个代码:
struct Test {
func run() {
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
print("pop")
}
}
}
let test = Test()
test.run()
Run Code Online (Sandbox Code Playgroud)
但没有什么是打印到控制台.我读过如何在Swift中使用NSTimer?我在网上的答案和教程中看到的计时器的大部分用法涉及一个选择器,所以我尝试了这个:
class Test {
func run() {
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.peep), userInfo: nil, repeats: false)
}
@objc func peep() {
print("peep")
}
}
let test = Test()
test.run()
Run Code Online (Sandbox Code Playgroud)
似乎仍然没有打印到控制台.如果我添加timer.fire(),那么我得到控制台打印,但显然这违背了目的.我需要更改什么才能让计时器运行?
编辑:
所以CFRunLoopRun()在我run为我的Teststruct 调用方法之后添加就可以了.非常感谢那些回答的人,特别是@AkshayYaduvanshi(他的评论指向我CFRunLoopRun())和@JoshCaswell(他的答案提出了我的计时器只适用于运行循环的事实).
我在Swift中使用"NSTimer.scheduledTimerWithTimeInterval"时看到的所有示例都使用"target:self"参数显示,但不幸的是,这在Swift Playgrounds中不起作用.
Playground execution failed: <EXPR>:42:13: error: use of unresolved
identifier 'self'
target: self,
Run Code Online (Sandbox Code Playgroud)
以上引用的示例导致错误:
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()
Run Code Online (Sandbox Code Playgroud)