ios - 使用字符串参数实现执行选择器

标签 ios swift string performselector

我需要从字符串实现一个执行选择器。 选择器必须有一个通知值作为参数。

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

我的方法基于:

最佳答案

我相信您必须在选择器字符串中包含参数名称和类名称,因此选择器字符串变为:

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

关于ios - 使用字符串参数实现执行选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45057915/

相关文章:

string - 使用 go 遍历批量字符串中的行

c++ - 高效的 const char* 连接和输出到 std::string

Swift:从 Internet 下载图像并缓存它们无法正常工作。需要建议

iOS10 iMessage : Unable to insert data into iMessage using MSConversation

ios - 在 iPhone 6 Plus 上关闭 UISplitViewController 弹出窗口时 UIWebView 拉伸(stretch)

iphone - 如何制作如附图所示的 View ?

swift - 为什么不 becomeFirstResponder 在警报消息文本字段上触发软键盘

xcode - xcode 6 中的 EXC_BREAKPOINT

java - java修改字符串

ios - 无法使用 '[NSAttributedString.Key : Any]' 类型的参数为 'String' 类型的值添加下标