美文网首页
Swift创建线程

Swift创建线程

作者: yaoxp | 来源:发表于2017-08-09 13:06 被阅读46次

    最近在对比Objective-c学习Swift

    创建线程执行一个方法就结束线程,这种可以用GCD或者queue实现,没必要浪费资源创建一个新线程。本文中说的创建线程是创建一个不会结束的线程

    直接上干货,Objective-c中创建线程参考AFNetworking 2中的方法:

    Jietu20170502-152309@2x.jpg

    Swift中创建不结束的线程同样需要显示的启动runloop

    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            
            createThreadOne()
            createThreadTwo()
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        func createThreadOne() {
            let newThread = Thread.init(target: self, selector: #selector(threadOne), object: nil)
            newThread.start()
        }
        
        func threadOne() {
            print("thread one func")
            Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { (timer) in
                print("thread one")
            })
            RunLoop.current.add(Port(), forMode: .commonModes)
            RunLoop.current.run()
        }
        
        func createThreadTwo() {
            Thread.detachNewThreadSelector(#selector(threadTwo), toTarget: self, with: nil)
        }
        
        func threadTwo() {
            print("thread two func")
            Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {
                (timer) in
                print("thread two")
            })
            RunLoop.current.add(Port(), forMode: .commonModes)
            RunLoop.current.run()
        }
    

    相关文章

      网友评论

          本文标题:Swift创建线程

          本文链接:https://www.haomeiwen.com/subject/cwgfrxtx.html