簡體   English   中英

使用來自字符串的參數實現執行選擇器

[英]Implement perform selector with parameter from a String

我需要從字符串實現一個性能選擇器。 選擇器必須具有通知值作為參數。

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]:無法識別的選擇器已發送到實例0x600000052c60

*由於未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:'-[ISAMGAME.ChapterClass catchNotificationParagraphFinished_Chapter2]:無法識別的選擇器已發送至實例0x600000052c60 **

我也嘗試過:

func catchNotificationParagraphFinished_Chapter2(_ notification:Notification) {}

並嘗試使用:

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

我的方法基於以下幾點:

我相信您必須在選擇器字符串中包含參數名稱以及類名稱,因此選擇器字符串變為:

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

我的方法工作正常,但不要忘記將String類型添加到常量中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM