swift 4.0中dispatch_async,dispatch_after的使用
2018年03月28日 16:15:44 xiao_yuly 阅读数:3576
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jacob_ios/article/details/79729251
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.08.15 15:44* 字数 206 阅读 1226评论 0喜欢 0
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
NSLog(@"延迟了5秒了");
});
1.performSelector方法
[self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
此方式要求必须在主线程中执行,否则无效。是一种非阻塞的执行方式,暂时未找到取消执行的方法。
2.定时器:NSTimer
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
此方式要求必须在主线程中执行,否则无效。是一种非阻塞的执行方式,可以通过NSTimer类的- (void)invalidate;取消执行。
3.sleep方式
[NSThread sleepForTimeInterval:1.0f]; [self delayMethod];
此方式在主线程和子线程中均可执行。是一种阻塞的执行方式,建方放到子线程中,以免卡住界面没有找到取消执行的方法。
4.GCD方式
double delayInSeconds = 1.0;
__block ViewController* bself = self;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[bself delayMethod];
});
此方式在可以在参数中选择执行的线程。是一种非阻塞的执行方式,没有找到取消执行的方法。
Swift3.0 延时执行
2016年10月25日
https://blog.csdn.net/c_calary/article/details/52917344
1.延时执行
//延时1秒执行
let time: TimeInterval = 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
//code
print("1 秒后输出")
}
2.对延时执行喵神进行了较好的封装,这里我也贴出来了,供大家学习
import Foundation
typealias Task = (_ cancel : Bool) -> Void
func delay(_ time: TimeInterval, task: @escaping ()->()) -> Task? {
func dispatch_later(block: @escaping ()->()) {
let t = DispatchTime.now() + time
DispatchQueue.main.asyncAfter(deadline: t, execute: block)
}
var closure: (()->Void)? = task
var result: Task?
let delayedClosure: Task = {
cancel in
if let internalClosure = closure {
if (cancel == false) {
DispatchQueue.main.async(execute: internalClosure)
}
}
closure = nil
result = nil
}
result = delayedClosure
dispatch_later {
if let delayedClosure = result {
delayedClosure(false)
}
}
return result
}
func cancel(_ task: Task?) {
task?(true)
}
/*****使用*****/
//调用
delay(2) { print("2 秒后输出") }
//取消
let task = delay(5) { print("拨打 110") }
// 仔细想一想..
// 还是取消为妙..
cancel(task)
摘录来自: 王巍 (onevcat). “Swifter - Swift 必备 Tips (第三版)”。 iBooks.
3.OC版本
//延时
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//do something
});