看了喵神的Swifter 100个必备的小tips总结下
swift中不支持@selector关键字,将SEL重新定义为结构体了。
但是NSSelectorFromString()依然可以使用,但是获取方法名的规则有点变动。
1.不带参数的方法
func normalSelector()
{
NSLog("normal")
}
let ts = TestSelector()
let ns = Selector("normalSelector")
ts.performSelector(ns)
func normalWithPara(name:String)
{
NSLog("para = %s",name)
}
func normalWithMorePara(name:String,age : Int)
{
NSLog("more para = %s %d",name,age)
}
let np = Selector("normalWithPara:")
ts.performSelector(np,withObject: "np")
let nmp = Selector("normalWithMorePara:age:")
ts.performSelector(nmp,withObject: "nmp",withObject:1)
"normalWithMorePara:age:" 参数中如果添加个空格变成 "normalWithMorePara: age:" 就会残忍的崩溃。。。
3.带外部参数名的方法,如果第一个参数有外部变量名,则需要方法名+With+外部参数名(第一个字母要大些),之后的参数有外部变量名的都是用外部变量名。
func outsideSelectorWithMorePara(name nm:String,age ag:Int)
{
NSLog("nm = %s,ag = %d",nm,ag)
}
func outsideSelector(name nm:String)
{
NSLog("nm = %s",nm)
}
let os = Selector("outsideSelectorWithName:")
ts.performSelector(os,withObject:"os")
let oms = Selector("outsideSelectorWithMoreParaWithName:age:")
ts.performSelector(oms,withObject: "oms",withObject: 1)