What is a selector in SKAction: perform(_:onTarget:)

孤者浪人 提交于 2019-12-10 17:42:42

问题


The docs say:

Declaration:

class func perform(_ selector: Selector, onTarget target: Any) -> SKAction

selector

The selector of the method to call.

I am uncertain what a selector of a method is. Hence the question.

It seems like it would be the name of the method/function, but creates (in me) uncertainty because it's never described as being this, so I kind of think it might be something else, something more profound, perhaps.

I'm presupposing perform(_:onTarget) is a way for a part of code to be flexibly telling an object decided at runtime what action to perform. But am not entirely sure that I have its purpose right. That's the context within which I'm thinking about this.

Not only is my question different from the linked "similar" question in terms of context, it's also a different, and much more specific question: WHAT is a selector in this particular function.


回答1:


A selector is the name of a function, and a target is an object on which to perform the function. You construct a selector using the syntax: #selector(<function name>), for example:

class MyClass {

    func createAction() {
        let action = SKAction.perform(#selector(MyClass.myActionFunction), onTarget: self)
        // ...
    }

    @objc func myActionFunction() {
        // do stuff
    }
}

To create a selector for a function that takes arguments, use the syntax:

#selector(MyClass.myActionFunction(arg1:arg2:))

You can also accomplish this same thing using a block instead of a selector:

let action = SKAction.run { [weak self] in
    self?.myActionFunction()
}


来源:https://stackoverflow.com/questions/40354537/what-is-a-selector-in-skaction-perform-ontarget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!