标签:gcd dispatch_after dispatch_apply dispatch_once
原创Blog,转载请注明出处
本文阅读的过程中,如有概念不懂,请参照前专栏中之前的文章,如果还有疑惑,请留言。
这是我关于GCD专栏的地址
http://blog.csdn.net/column/details/swift-gcd.html
func dispatch_after(_ when: dispatch_time_t, _ queue: dispatch_queue_t!, _ block: dispatch_block_t!)参数
when 过了多久执行的时间间隔 queue 提交到的队列 block 执行的任务
func hwcDelay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) }
class ViewController: UIViewController{ func hwcDelay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } override func viewDidLoad(){ super.viewDidLoad() hwcDelay(1.0){ var alertview = UIAlertView(title:"Dispatch_after",message:"Message",delegate:self,cancelButtonTitle:"OK") alertview.show() } } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() } }
func dispatch_apply(_ iterations: UInt, _ queue: dispatch_queue_t!, _ block: ((UInt) -> Void)!)参数
iterations 执行的次数 queue 提交到的队列 block 执行的任务
class ViewController: UIViewController{ var hwcarray = ["hello","hwc","hellohwc"] override func viewDidLoad(){ super.viewDidLoad() dispatch_apply(3,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)){ (index:UInt) -> () in var expObject = self.hwcarray[Int(index)] as NSString NSLog("%d",expObject.length) } NSLog("Dispatch_after is over") } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() } }可以看到,输出是
3 5 8 dispatch_after is over由于这样会阻塞主线程,而下文又与dispatch_apply的执行结果无关,所以可以在异步队列中掉dispatch_apply,然后执行完成后进行通知
class ViewController: UIViewController{ var hwcarray = ["hello","hwc","hellohwc"] override func viewDidLoad(){ super.viewDidLoad() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)){ dispatch_apply(3,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)){ (index:UInt) -> () in var expObject = self.hwcarray[Int(index)] as NSString NSLog("%d",expObject.length) } NSLog("Dispatch_after in global queue is over") } NSLog("Dispatch_after in main queue is over") } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() } }这样输出为
8 Dispatch_after in main queue is over 3 5 Dispatch_after in global queue is over可以看到,相对主队列(主线程)是异步的,在global队列中是并行执行的
class hwcSingleton { var testVariable:Int! func print(){ testVariable = testVariable + 1 println(testVariable) } class var sharedObject: hwcSingleton { struct StaticStruct { static var predicate : dispatch_once_t = 0 static var instance : hwcSingleton? = nil } dispatch_once(&StaticStruct.predicate) { StaticStruct.instance = hwcSingleton() StaticStruct.instance?.testVariable = 10 } return StaticStruct.instance! } }
完整详解GCD系列(二)dispatch_after;dispatch_apply;dispatch_once
标签:gcd dispatch_after dispatch_apply dispatch_once
原文地址:http://blog.csdn.net/hello_hwc/article/details/41204027