码迷,mamicode.com
首页 > 移动开发 > 详细

iOS gcd dispatch使用注意

时间:2015-04-03 00:03:51      阅读:145      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!