Creating threads in swift?

I am trying to create a thread in swift. So, I have this line:

. ,.

let thread = NSThread(target: self, selector: doSomething(), object: nil) 

. ,.

doSomething is a function within the class.

This line gives this error: "could not find an overload for init () that takes the supplied arguments"

What am I missing here? Ho can I create a new thread in swift?

+6
source share
3 answers

Starting with Xcode 7.3 and Swift 2.2, you can use the special form #selector(...) , where Objective-C will use @selector(...) :

 let thread = NSThread(target:self, selector:#selector(doSomething), object:nil) 
+12
source

NSThread takes a selector as the second parameter. You can describe the Objective-C selector as strings in Swift as follows:

 let thread = NSThread(target: myObj, selector: "mySelector", object: nil) 

Swift functions are not equivalent to Objective-C. If you have a method in a fast class, you can use it as a selector if you use the @objc attribute for the class:

 @objc class myClass{ func myFunc(){ } } var myObj = myClass() let thread = NSThread(target: myObj, selector: "myFunc", object: nil) 
+4
source
  • When we call the selector on the target, we need to check if the target exists, and it responds to the selector. Only a class that extends from NSObject or its subclasses can use respondsToSelector:

  • You can use NSDictionary to store parameters if you have more than two parameters.

    Example:

     //this code is in Objective-C but the same code should exist in Swift NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:object1, @"key1", object2, @"key2",nil]; 

then pass "params" to the selector parameter:

0
source

Source: https://habr.com/ru/post/971679/


All Articles