Search code examples
iosswiftstringperformselector

Implement perform selector with parameter from a String


I need to implement a perform selector from a String. The Selector must have as parameter a Notification value.

class ChapterViewController: UIViewController {

    var chapterClass:ChapterClass!

    func catchNotificationParagraphFinished(notification:Notification) {

        let name = "catchNotificationParagraphFinished_\(chapter.className!)"
        let selector = NSSelectorFromString(name)

        chapterClass.perform(selector, with: notification)   
    }
}

    class ChapterClass: NSObject {

        func catchNotificationParagraphFinished_Chapter2(notification:Notification) {}
    }

I suppose I'm doing something wrong, because I got this error:

[ISAMGAME.ChapterClass catchNotificationParagraphFinished_Chapter2]: unrecognized selector sent to instance 0x600000052c60

*Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ISAMGAME.ChapterClass catchNotificationParagraphFinished_Chapter2]: unrecognized selector sent to instance 0x600000052c60**

I also tried with:

func catchNotificationParagraphFinished_Chapter2(_ notification:Notification) {}

And also tried using:

let name = "catchNotificationParagraphFinished_\(chapter.className!):"
let selector = Selector((name))

I based my approach thanks to:


Solution

  • My method works fine, but don't forget to add String type to the constant...

     let name:String = "catchNotificationParagraphFinished_\(chapter.className!):"