0

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:

Amal T S
  • 3,327
  • 2
  • 24
  • 57
cmii
  • 3,556
  • 8
  • 38
  • 69

2 Answers2

0

I believe you have to include the parameter name as well as class name in the selector string, therefore the selector string becomes:

let name = "ChapterClass.catchNotificationParagraphFinished_\(chapter.className!)(notification:)"
genghiskhan
  • 1,095
  • 12
  • 21
  • I really need to create my selector from String. Depending of the string, I will call catchNotificationParagraphFinished_Chapter2 or catchNotificationParagraphFinished_Chapter3... etc... I like to avoid to have many "if" conditions. – cmii Jul 12 '17 at 12:58
  • Same crash "[ISAMGAME.ChapterClass catchNotificationParagraphFinished_Chapter2(notification:)]: unrecognized selector sent to instance" :( – cmii Jul 12 '17 at 13:35
  • It could be that you can't perform a selector on a class outside of the current class, therefore try calling a method in ChapterClass that is passed a class name and performs the selector on itself – genghiskhan Jul 12 '17 at 13:52
  • It was a good idea, but I have just tried and the same error appears ... – cmii Jul 12 '17 at 14:07
0

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

 let name:String = "catchNotificationParagraphFinished_\(chapter.className!):"
cmii
  • 3,556
  • 8
  • 38
  • 69