首页 > 移动平台 > 详细

iOS gcd dispatch使用注意

时间:2015-04-03 00:01:46      阅读:373      评论:0      收藏:0      [点我收藏+]
class ViewController: UIViewController {
    var dbQueue:dispatch_queue_t = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        dbQueue = dispatch_queue_create("com.Innocellence.sunflower", nil)
    
        //do some work in dbQueue from main thread
        dispatch_sync(dbQueue, { () -> Void in
  
            //do some work in main thread from dbQueue
            dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                self.test()
            })
            
        })
        
        println("this is some other code")

    }
    
    func test(){
        
        println("this is test")
    
    
    }


}

 

上面这段代码,是错误的,viewdidload无法执行完

再把代码稍微换下

 

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        dbQueue = dispatch_queue_create("com.Innocellence.sunflower", nil)
    
        //do some work in dbQueue from main thread
        dispatch_async(dbQueue, { () -> Void in
  
            //do some work in main thread from dbQueue
            dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                self.test()
            })
            
        })
        
        println("this is some other code")

    }

这个是有输出的,结果是

this is some other code

this is test

 

再变成下面这个

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        dbQueue = dispatch_queue_create("com.Innocellence.sunflower", nil)
    
        //do some work in dbQueue from main thread
        dispatch_sync(dbQueue, { () -> Void in
  
            //do some work in main thread from dbQueue
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.test()
            })
            
        })
        
        println("this is some other code")

    }

输出如下

this is some other code


this is test

第一个为什么无法继续执行了呢,首先代码阻塞了主线程的执行,要求在新线程执行完后才返回,但是新线程也被阻塞了,要求代码在主线程完成后才能返回,这样就形成了循环。这里线程这个词用的不准,其实紧紧是线程中执行的一段顺序代码。还需要仔细研究原因!

 

 

iOS gcd dispatch使用注意

原文:http://www.cnblogs.com/breezemist/p/4388564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!