Sunday, September 28, 2014

Swift - Using Selector in Swift

In Objective-C, you often encounter methods that accepts a Selector as the argument. A good example is the NSTimer's NSTimer.scheduledTimerWithTimeInterval() method:

- (void)onTimer {
}

    [NSTimer scheduledTimerWithTimeInterval:0.05
                                     target:self
                                   selector:@selector(onTimer)
                                   userInfo:nil
                                    repeats:YES];   


A selector is basically a name of a method that will be executed by another method. In Objective-C, to pass in a selector argument you use the @selector() keyword together with the name of the method. 

In Swift, you can simply pass in the name of the method as a string, like this:

func onTimer() {
}

        NSTimer.scheduledTimerWithTimeInterval(0.05,
            target:self,
            selector:"onTimer",
            userInfo:nil,
        repeats:true)

No comments: