使用字符串中的参数实现执行选择器
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]: 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))
我的方法基于以下原因:
我认为您必须在选择器字符串中包括参数名称和 class 名称,因此选择器字符串变为:
let name = "ChapterClass.catchNotificationParagraphFinished_\(chapter.className!)(notification:)"
我的方法没问题,但是不要忘记给常量加上String类型...
let name:String = "catchNotificationParagraphFinished_\(chapter.className!):"
我需要从字符串中实现一个执行选择器。 选择器必须有一个通知值作为参数。
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))
我的方法基于以下原因:
我认为您必须在选择器字符串中包括参数名称和 class 名称,因此选择器字符串变为:
let name = "ChapterClass.catchNotificationParagraphFinished_\(chapter.className!)(notification:)"
我的方法没问题,但是不要忘记给常量加上String类型...
let name:String = "catchNotificationParagraphFinished_\(chapter.className!):"