使用NSThread产生线程时如何解决“目标没有实现选择器”这个异常?

时间:2021-12-30 20:58:53

I am a pretty new in use NSThread to spawn thread. In my practise, I want to spawn a thread to execute a method that print a String in CreateThread Class. But when I run my program, "target does not implement selector" exception is displayed in the console. How I should to be done in order to resolve this problem? Thanks for answer.

我是一个非常新的使用NSThread产生线程。在我的实践中,我想生成一个线程来执行一个在CreateThread类中打印String的方法。但是当我运行我的程序时,“目标没有实现选择器”异常会显示在控制台中。我该怎么做才能解决这个问题?谢谢你的回答。

Code below:

import Foundation

class CreateThread {

func HelloWorld() {

    print("Hello World!")

    NSThread.detachNewThreadSelector("secondaryThreadMethod", toTarget: self, withObject: nil)

    print("Test")

}

func secondaryThreadMethod() {

    print("Hello World in Secondary Thread!")

}

}

let createThread = CreateThread()
createThread.HelloWorld()

1 个解决方案

#1


1  

The problem is NSThread api operates in objective-c runtime and your CreateThread class is pure swift - by default its methods are not visible in objective-c world. To solve that you can make your class inherit from NSObject or mark your secondaryThreadMethod method as @objc:

问题是NSThread api在objective-c运行时运行,而你的CreateThread类是纯swift - 默认情况下,它的方法在objective-c世界中不可见。要解决这个问题,你可以让你的类继承自NSObject,或者将secondaryThreadMethod方法标记为@objc:

// Either of following lines will fix the crash
class CreateThread : NSObject {
...
@objc func secondaryThreadMethod() {

You can read more about swift and objective-c interoperability in documentation

您可以在文档中阅读有关swift和objective-c互操作性的更多信息

#1


1  

The problem is NSThread api operates in objective-c runtime and your CreateThread class is pure swift - by default its methods are not visible in objective-c world. To solve that you can make your class inherit from NSObject or mark your secondaryThreadMethod method as @objc:

问题是NSThread api在objective-c运行时运行,而你的CreateThread类是纯swift - 默认情况下,它的方法在objective-c世界中不可见。要解决这个问题,你可以让你的类继承自NSObject,或者将secondaryThreadMethod方法标记为@objc:

// Either of following lines will fix the crash
class CreateThread : NSObject {
...
@objc func secondaryThreadMethod() {

You can read more about swift and objective-c interoperability in documentation

您可以在文档中阅读有关swift和objective-c互操作性的更多信息