swift里面没有performSelector,有替代的函数吗

swift里面没有performSelector,有替代的函数吗


慕尼黑的夜晚无繁华
浏览 1490回答 2
2回答

侃侃无极

使用可选链调用。例如试图调用代理中一个叫 abc 的没参数的方法:delegate?abc?()就等于判断了 delegate 是否为 nil,而 delegate 不为 nil 的时候又执行了 performSelector 判断 abc 是否存在了。如果 delegate == nil 或者 abc 不存在,都不会干任何事情,不会异常出错。而如果 delegate 不为空,abc 方法存在,则会正常调用 delegate 里的 abc 方法。

波斯汪

Swift由于并非基于消息机制,所以本身没有selector这个十分灵活的机制,但是可以使用Cocoa Framework中所留下的一些selector,比如:<pre class="brush:objc; toolbar: true; auto-links: false;">import UIKitclass MyViewController: UIViewController {let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {super.init(nibName: nibName, bundle: nibBundle) myButton.targetForAction("tappedButton:", withSender: self)}func tappedButton(sender: UIButton!) { println("tapped button")} }</pre>上述代码,"tappedButton:"就是一个selector,呵呵。
打开App,查看更多内容
随时随地看视频慕课网APP