简体   繁体   中英

Handle the selector parameter in swift

Let's say I declare a function in my CustomTimer class:

class CustomTimer {

    class func scheduledTimerWithSelector(aSelector: Selector) -> CustomTimer {
     // aSelector ??
    }
}

How can I handle this aSelector parameter?

Like the NSTimer.scheduledTimerWithTimeInterval method, how dose it work?

You should check the Selector structure. From the apple docs:

In Swift, Objective-C selectors are represented by the Selector structure. You can construct a selector with a string literal, such as let mySelector: Selector = "tappedButton:". Because string literals can be automatically converted to selectors, you can pass a string literal to any method that accepts a selector.

Selector function with Swift :

func selectorFunc(aSel:Selector){
    if self.respondsToSelector(aSel){
        NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: aSel, userInfo: nil, repeats: false)
    }
}

func gooleIt(){
    println("Hello")
}

Function Call :

self.selectorFunc(Selector(gooleIt()))

Hope it help you.

You can declare a method with a selector like this and you can call it by creating a UIControl because performSelector methods are not available in Swift:

func methodWithSelector(sel:Selector) {
        var control = UIControl()
        control.sendAction(sel, to: self, forEvent: nil)
}

If you do not need to call it on the main thread another option is like this:

func methodWithSelector(sel:Selector) {
    NSThread.detachNewThreadSelector(sel, toTarget: self, withObject: nil)
}

You will call it like this:

methodWithSelector(Selector("methodCall"))

or like this

methodWithSelector("methodCall")

then you must have a method with the name of the selector

func methodCall() {
        println("methodCall")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM