2016-11-08 14:09:57 asuno_1 阅读数 1312

swift的延时操作方法 主要是int64这边 和 oc 有点区别

 let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC)))

        dispatch_after(delayTime, dispatch_get_main_queue(), { 

            //延时操作

            print("这边延时了1")

        })



2018-03-28 16:15:44 jacob_ios 阅读数 8239

Swift 2.x

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    let image = self.loadImage()
    // 回到主线程更新UI
    dispatch_async(dispatch_get_main_queue()) {
        self.imageView.image = image
    }
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
    print("test")
}

Swift 4.0

DispatchQueue.global(qos: .userInitiated).async {
    let image = self.loadImage()
    // back to the main thread 
    DispatchQueue.main.async {
        self.imageView.image = image
    }
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) { 
    print("Are we there yet?")
}



2016-09-23 10:57:58 mydo 阅读数 9882

在Swift中如果想搞类的单例模式,那么在初始化的时候一般会使用just one time执行的方式,我们使用dispatch_once_t配合调用dispatch_once方法,一般的代码如下:

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.")
    }
}

不过在Swift3中会提示此法行不通,dispatch_xxx已废弃,use lazily initialized globals instead.

原来自从swift 1.x开始swift就已经开始用dispatch_one机制在后台支持线程安全的全局lazy初始化和静态属性.所以static var背后已经在使用dispatch_once了.网友的解释是:

So the static var above was already using dispatch_once, which makes it sort of weird (and possibly problematic to use it again as a token for another dispatch_once. In fact there's really no safe way to use dispatch_once without this kind of recursion, so they got rid of it. Instead, just use the language features built on it

所以现在的swift3中干脆把dispatch_once显式的取消了.

我们再Swift3中若要想实现原来dispatch_once的机制可以用以下几种办法:

1.使用全局常量

let foo = SomeClass()

2.带立即执行闭包初始化器的全局变量:

var bar: SomeClass = {
    let b = SomeClass()
    b.someProperty = "whatever"
    b.doSomeStuff()
    return b
}()

3.类,结构,枚举中的静态属性:

class MyClass {
    static let singleton = MyClass()
    init() {
        print("foo")
    }
}

你还可以直接创建一个全局的变量或静态属性来达到没有结果的just one time:

let justAOneTimeThing: () = {
    print("Not coming back here.")
}()

如果你觉得这都不和你的胃口,你可以在需要调用justAOneTimeThing的地方直接调用它就是啦:

func doTheOneTimeThing() {
    justAOneTimeThing
}

所以在Swift3中推荐使用如下方法来完成一个单例:

class Foo{
    private static let sharedInstance = Foo()
    class var sharedFoo {
        return sharedInstance
    }
}
2016-11-29 19:20:56 ch_quan 阅读数 6580

dispatch_after 的swift 3 版本,百度找了半天都是旧版本的,上stackover flow才找到新版本..分亨出来.
如果不需要在主线程执行,就去掉main 
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your code here
}

Swift中的dispatch_once

阅读数 364

Swift单例的写法

阅读数 507

没有更多推荐了,返回首页