Swift presentViewController完成块仅在未在发布中调用的调试中工作

时间:2015-03-16 08:09:53

标签: swift closures completion-block

我在Debug和Release中有一个完成块的奇怪行为。 例如:

        sourceViewController.presentViewController(ccVC, animated: true, completion: { () -> Void in
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: kChromeCastInstructionsShown)
            NSUserDefaults.standardUserDefaults().synchronize()
            println("save bolean")
        })

在调试中:    println(" save bolean")print string 在重新:  println(" save bolean")什么都不打印

有关此行为的任何想法? 有人试验了一个明确的解决方案吗?

类 安德烈

2 个答案:

答案 0 :(得分:10)

它看起来像这里讨论的Swift编译器错误(至少版本1.1): https://github.com/ReactiveCocoa/ReactiveCocoa/issues/1632

在发布版本中,有时不会调用闭包,特别是当它们按顺序排序时:

array.map({ $0 * 2 }).map({ $0 * 3 }).map({ $0 * 4 })...

问题仅出现在Swift中,而不是出现在Objective-C中。如果您的应用程序不需要通过优化获得更好的性能,可以通过将Swift编译器优化级别设置为无[-Onone] 来进行设计。

Screenshot

或者另一种解决方法是将闭包命名为函数:

func completionHandler() {
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: kChromeCastInstructionsShown)
    NSUserDefaults.standardUserDefaults().synchronize()
    println("save bolean")
}

sourceViewController.presentViewController(ccVC, animated: true, completion: completionHandler)

我为我的项目采用以前的解决方法,因为我希望保持代码简单,不需要通过优化提高性能。

答案 1 :(得分:0)

我在xcode 7中发现了同样的问题。 例如

  let delay = 0.2 * Double(NSEC_PER_SEC)
  let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

            dispatch_after(time, dispatch_get_main_queue(), {



            })

仅当我还设置了优化级别无[-OO]

时才有效