好的,所以我在Xcode 8中发现了新的Swifty Dispatch API.我很开心使用DispatchQueue.main.async,我一直在浏览DispatchXcode中的模块以找到所有新的API.
但我也用它dispatch_once来确保像单例创建和一次性设置这样的事情不会被多次执行(即使在多线程环境中)......并且dispatch_once在新的Dispatch模块中找不到它?
static var token: dispatch_once_t = 0
func whatDoYouHear() {
print("All of this has happened before, and all of it will happen again.")
dispatch_once(&token) {
print("Except this part.")
}
}
Run Code Online (Sandbox Code Playgroud) 我在Swift中做了这个简单的扩展:
extension DispatchQueue {
func asyncAfter(delay: TimeInterval, block: @escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: block)
}
}
Run Code Online (Sandbox Code Playgroud)
在Project-Swift.h头文件中,它报告此行的错误:
@interface OS_dispatch_queue (SWIFT_EXTENSION(...))
- (void)asyncAfterDelay:(NSTimeInterval)delay block:(void (^ _Nonnull)(void))block;
@end
Run Code Online (Sandbox Code Playgroud)
错误是:找不到'OS_dispatch_queue'的接口声明
有没有办法阻止为Objective-C导出扩展?或者有办法解决错误吗?
编写一段只能执行一次的代码的最简单方法是什么?
我知道一种方法但有问题.
首先,我写了一个布尔变量,它具有负值,但可以设置为正值,之后不能更改
var hasTheFunctionCalled : Bool = false {
didSet{
hasTheFunctionCalled = true
}
}
Run Code Online (Sandbox Code Playgroud)
然后在其中编写函数和代码:
func theFunction(){
if !hasTheFunctionCalled{
//do the thing
}
hasTheFunctionCalled = true
}
Run Code Online (Sandbox Code Playgroud)
但问题是变量可以从范围内的其他地方更改,这个解决方案看起来并不那么简单和具体.