我在 Debug 和 Release 中有一个完成 block 的奇怪行为。 例如:
sourceViewController.presentViewController(ccVC, animated: true, completion: { () -> Void in
NSUserDefaults.standardUserDefaults().setBool(true, forKey: kChromeCastInstructionsShown)
NSUserDefaults.standardUserDefaults().synchronize()
println("save bolean")
})
调试中: println("保存 bool 值") 打印字符串 在释放: println("save bolean") 什么都不打印
对这种行为有什么想法吗? 有人试验了一种清晰的解决方案吗?
善良 安德里亚
最佳答案
它看起来是这里讨论的 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] 来解决此问题。
或者另一种解决方法是将闭包命名为函数:
func completionHandler() {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: kChromeCastInstructionsShown)
NSUserDefaults.standardUserDefaults().synchronize()
println("save bolean")
}
sourceViewController.presentViewController(ccVC, animated: true, completion: completionHandler)
我为我的项目采用了以前的解决方法,因为我想让我的代码保持简单并且不需要通过优化来增强性能。
关于Swift presentViewController 完成 block 仅在调试中工作,未在发布中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29072139/