ios - For Loop Swift 中的闭包完成

标签 ios swift for-loop closures

我有一组对象都需要验证。验证需要使用闭包。

我知道闭包可以随时完成,因此 for 循环将在所有闭包之前完成。所以在 for 循环之后放类似 reloadData 的东西是行不通的。

那么,对于每个经过循环的对象,了解所有闭包代码何时完成的好方法是什么?

我可以在闭包中调用 reloadData 并一次更新一个数据 - 但宁愿在它们全部完成后才这样做。

我的代码

    for aClient in passedPossible {

        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(aClient[address], completionHandler: { (placemarks, error) -> Void in
            if let placemarks = placemarks as? [CLPlacemark] {
                // found it do stuff
            }
            else {
                // do stuff as cannot find
            }
        })
    }

    // how to reload at the end of the for loop
    self.tableView.reloadData()

最佳答案

我建议对每个地理编码回调使用 tableView.reloadRowsAtIndexPaths。

但是如果您必须使用 reloadData(),最简单的解决方案是计算您的地理编码作业以防止重新进入。

例子:

var loading =   false

@IBAction func
Do( sender: AnyObject ) {

    if !loading {
        loading = true
        var w = 0
        for i in 0 ..< 10 {
            dispatch_async( dispatch_get_main_queue() ) {
                println( i )
                if ++w == 10 {
                    self.loading = false
                    println( "It's time to call reloaddata!" )
                }
            }
        }
    }
}

编辑:

如何附加工作 ID 之类的内容并将其放入列表中?

var jobIDs: [ Int ] =   []

@IBAction func
Do( sender: AnyObject ) {

    if jobIDs.count == 0 {
        for theJobID in 0 ..< 10 {
            jobIDs.append( theJobID )
            dispatch_async( dispatch_get_main_queue() ) {
                println( "Doing job:\(theJobID)" )
                self.jobIDs.removeAtIndex( find( self.jobIDs, theJobID )! )
                if self.jobIDs.count == 0 {
                    println( "It's time to call reloaddata!" )
                }
            }
        }
    }
}

您可以使用“aClient”作为作业 ID。

关于ios - For Loop Swift 中的闭包完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838691/

相关文章:

ios - 如何在 Xcode 的 Interface Builder 中一次编辑多个约束

objective-c - 将 Swift 3 升级到 4, objective-c 中不再有 swift 扩展

ios - 子类中是否有符合自定义协议(protocol)的常规空白函数?

ios - 使用 KVO 时这是否被认为是良好的编程实践

ios - API 未在 iOS 版 Swift 中显示数据

c++ - 将数组的所有元素初始化为相同的数字

python - 如何将数组中的每个元素与大数相乘而不会出现 OverflowError : Python int too large to convert to C long?

javascript - 数据角色中断 "for loop' 为什么

android - 使用网页链接访问移动 GPS 应用程序并将当前位置传递给应用程序

iphone - 链接器命令失败,PubNub 库在 swift 和静态框架中