暂停和恢复for循环 [英] Pause and Resume a for Loop
问题描述
我需要一些方法来暂停并重新开始 for
循环。我有这样的代码:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $($ i $ 0 $ i $ paramsArray.count; i ++){
var stringResponse:String!
var urlString:String
if paramsArray [i] .arduinoHTTPPort == 80 {
urlString = String(format:http://%@ / arduino /%@ /%i / ,参数:[paramsArray [i] .arduinoAddress,paramsArray [i] .pinType.lowercaseString,paramsArray [i] .arduinoPin])
} else {
urlString = String(format:http:// %@:%i / arduino /%@ /%i /,参数:[paramsArray [i] .arduinoAddress,paramsArray [i] .arduinoHTTPPort,paramsArray [i] .pinType.lowercaseString,paramsArray [i] .arduinoPin])
}
let url = NSURL(string:urlString)
let request = NSURLRequest(URL:url!)
NSURLConnection.sendAsynchronousRequest(request,queue:NSOperationQueue.mainQueue())
println(NSString(data:data,encoding:NSUTF8StringEncoding))
stringResponse = NSString(data:data,encoding:NSUTF8StringEncoding)中的{(response,data,error) String
//需要在这里恢复循环
//需要停止循环
code $
如何在swift中停止和恢复循环,或者有什么其他的方法来做这样的停止?
不是直接在循环中执行URL连接,而是在循环中创建 NSOperation
实例并将它们添加到 NSOperationQueue
。您可以挂起
和 resume
队列,并且您还可以设置 maxConcurrentOperationCount
,所以你可以限制你一次加载多少个连接。
I need some way to pause and resume for
loop. I have this code:
for (var i = 0; i < paramsArray.count; i++) {
var stringResponse: String!
var urlString: String
if paramsArray[i].arduinoHTTPPort == 80 {
urlString = String(format: "http://%@/arduino/%@/%i/", arguments: [paramsArray[i].arduinoAddress, paramsArray[i].pinType.lowercaseString, paramsArray[i].arduinoPin])
} else {
urlString = String(format: "http://%@:%i/arduino/%@/%i/", arguments: [paramsArray[i].arduinoAddress, paramsArray[i].arduinoHTTPPort, paramsArray[i].pinType.lowercaseString, paramsArray[i].arduinoPin])
}
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
stringResponse = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
//Need to resume loop here
}
//Need to stop loop here
}
How to stop and resume loop in swift, or is there any other ways to do such stops?
Don't think of it as pausing a loop, think of the loop as building the number of things you need to manage and then managing when those things are done after the loop is complete.
Rather than directly execute your URL connections in the loop you should create NSOperation
instances in the loop and add them to an NSOperationQueue
. You can suspend
and resume
the queue, and you can also set the maxConcurrentOperationCount
so you can limit how many connections you're loading at once.
这篇关于暂停和恢复for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!