【问题标题】:Implement perform selector with parameter from a String使用字符串中的参数实现执行选择器
【发布时间】:2017-07-12 22:49:04
【问题描述】:

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

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

我的方法基于:

【问题讨论】:

    标签: ios swift string performselector


    【解决方案1】:

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

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

    【讨论】:

    • 我真的需要从字符串创建我的选择器。根据字符串的不同,我会调用 catchNotificationParagraphFinished_Chapter2 或 catchNotificationParagraphFinished_Chapter3... 等等...我喜欢避免有很多“if”条件。
    • 同样的崩溃“[ISAMGAME.ChapterClass catchNotificationParagraphFinished_Chapter2(notification:)]: unrecognized selector sent to instance”:(
    • 可能是你不能在当前类之外的类上执行选择器,因此尝试调用ChapterClass中的一个方法,该方法传递一个类名并在自身上执行选择器
    • 这是个好主意,但我刚刚尝试并出现同样的错误......
    【解决方案2】:

    我的方法工作正常,但不要忘记给常量添加 String 类型...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      相关资源
      最近更新 更多