在swift中创建简单的线程会产生错误

时间:2015-08-15 11:38:35

标签: ios iphone multithreading swift

我正在尝试在swift和按钮单击启动时创建一个简单的线程,但它会抛出错误

"**Cannot find an initializer for type 'NSThread' that accepts an argument list of type ('target:ViewControllerm-> ())'**

这是我的代码:

import UIKit

class ViewController: UIViewController {

    var isSet = true          
    let thread123 = NSThread(target: self, selector: "myFunc", object: nil)

    func myFunc() {
    }

    @IBAction func btnClickEvent(sender: AnyObject) {
        // starting thread
        thread12.start()   
    }

}

我在这里做错了什么?

2 个答案:

答案 0 :(得分:4)

错误消息非常混乱。尝试将其重写为

let thread123:NSThread

init() {
    thread123 = NSThread(target: self, selector: "myFunc", object: nil)
}

你得到一条更清晰的错误信息,告诉你自己还没有

SO:

let thread123:NSThread

init() {
    super.init()
    thread123 = NSThread(target: self, selector: "myFunc", object: nil)
}

现在常量在调用超级之前没有初始化..也是一个nogo

所以

var thread123:NSThread!

init() {
    super.init(nibName: nil, bundle: nil)
    thread123 = NSThread(target: self, selector: "myFunc", object: nil)
}

或短暂和甜蜜

lazy var thread123:NSThread = NSThread(target: self, selector: "myFunc", object: nil)

答案 1 :(得分:2)

尝试替换此行

let thread123 = NSThread(target: self, selector: "myFunc", object: nil)

lazy var thread123:NSThread =
    {
        return NSThread(target: self, selector: "myFunc", object: nil)
    }()