cybergeeeek
cybergeeeek

Reputation: 430

creating simple thread in swift gives error

I'm trying to create a simple thread in swift and on button click starting but it throws an error

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

Here is my code:

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()   
    }

}

What am I doing wrong here?

Upvotes: 2

Views: 162

Answers (2)

Daij-Djan
Daij-Djan

Reputation: 50089

the error message is quite confusing. try rewriting it as

let thread123:NSThread

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

and you get a cleaner error message that shows you that self isn't there yet

SO:

let thread123:NSThread

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

now the constant isn't initialised before calling super.. also a nogo

so

var thread123:NSThread!

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

OR SHORT AND SWEET

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

Upvotes: 4

JulianM
JulianM

Reputation: 2550

Try to replace this line

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

with

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

Upvotes: 2

Related Questions