我需要實現字符串的執行選擇器。 選擇器必須具有一個通知值作爲參數。執行帶字符串參數的選擇器
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))
我基於我的方法感謝:
我真的需要從字符串創建我的選擇器。根據字符串,我會調用catchNotificationParagraphFinished_Chapter2或catchNotificationParagraphFinished_Chapter3 ...等...我喜歡避免有許多「如果」條件。 – cmii
我明白了,我編輯了我的答案以反映這一點。 – genghiskhan
相同的崩潰「[ISAMGAME.ChapterClass catchNotificationParagraphFinished_Chapter2(通知:)]:無法識別的選擇器發送到實例」:( – cmii