2017-07-12 59 views
0

我需要實現字符串的執行選擇器。 選擇器必須具有一個通知值作爲參數。執行帶字符串參數的選擇器

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) {} 
    } 

我想我做錯了什麼,因爲我得到這個錯誤:

[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**

我也試圖與:

func catchNotificationParagraphFinished_Chapter2(_ notification:Notification) {} 

而且使用也嘗試:

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

我基於我的方法感謝:

回答

0

我的方法工作正常,但不要忘記添加S tring類型的常量...

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

我認爲你必須包括在選擇字符串參數名稱以及類名,所以選擇字符串變成:

let name = "ChapterClass.catchNotificationParagraphFinished_\(chapter.className!)(notification:)" 
+0

我真的需要從字符串創建我的選擇器。根據字符串,我會調用catchNotificationParagraphFinished_Chapter2或catchNotificationParagraphFinished_Chapter3 ...等...我喜歡避免有許多「如果」條件。 – cmii

+0

我明白了,我編輯了我的答案以反映這一點。 – genghiskhan

+0

相同的崩潰「[ISAMGAME.ChapterClass catchNotificationParagraphFinished_Chapter2(通知:)]:無法識別的選擇器發送到實例」:( – cmii

相關問題