Reputation: 31
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc class myClass:NSObject {
func myFunc(){
for var i = 0; i < 10000; i++ {
print(i,[NSThread.currentThread()]);
}
}
}
var myObj = myClass()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
_ = NSThread.init(target: myObj, selector:Selector(myObj.myFunc()),
object: nil)
}
}
when I run the code above, Xcode has a exception.the information is
[NSThread initWithTarget:selector:object:]: target does not implement selector
how to use performSelectorInBackground in swift ??
Upvotes: 3
Views: 2910
Reputation: 1061
Note the latest syntax for performing a task in the background is:
let backgroundQueue = DispatchQueue.global(qos: .background)
backgroundQueue.async {
// Do stuff in the background
DispatchQueue.main.async {
// Pass to the main queue for UI work etc
}
}
If you're referring to self
in the background queue you probably want to add [weak self] in
after the .async {
.
Upvotes: 0
Reputation: 1103
This Worked for me
performSelector(inBackground: #selector(Selection_Button(url:)), with: finalPath2)
Upvotes: 0
Reputation: 31
Two points need to pay attention:
first, the class which use performSelectorInBackground must inhert NSObject.
second,performSelectorInBackground(Selector("myFunc"), withObject: nil)
is correct. myFunc is function name.
Upvotes: 0
Reputation: 14504
You can use perform selector as below:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
_ = NSThread.init(target: myObj, selector:Selector("myFunc"),
object: nil)
}
To perform some task in background you can use dispatcher as an alternative for performSelectorInBackground.
let backgroundQueue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
dispatch_async(backgroundQueue) { () -> Void in
self.myFunc()
}
Upvotes: 0
Reputation: 1498
A Selector
is associated with the name of a method represented as a String
. You're not properly initializing the Selector
. Selector
has an initializer that takes a String
, so you shouldn't be passing it myObj.myFunc()
. Instead you should be passing it "myFunc"
. See this question for more detail:
@selector() in Swift?
Upvotes: 1