2 回答

TA貢獻2051條經驗 獲得超10個贊
使用可選鏈調用。例如試圖調用代理中一個叫 abc 的沒參數的方法:
delegate?abc?()
就等于判斷了 delegate 是否為 nil,而 delegate 不為 nil 的時候又執行了 performSelector 判斷 abc 是否存在了。
如果 delegate == nil 或者 abc 不存在,都不會干任何事情,不會異常出錯。
而如果 delegate 不為空,abc 方法存在,則會正常調用 delegate 里的 abc 方法。

TA貢獻1811條經驗 獲得超4個贊
Swift由于并非基于消息機制,所以本身沒有selector這個十分靈活的機制,但是可以使用Cocoa Framework中所留下的一些selector,比如:
<pre class="brush:objc; toolbar: true; auto-links: false;">
import UIKit
class 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,呵呵。
- 2 回答
- 0 關注
- 1564 瀏覽
添加回答
舉報