代表 – 通过Swift访问代理的正确方法是什么?

我试图模拟使用
Swift访问对象委托的Objective-C模式.通常我会将协议放在两个UIViewControllers之间共享的.h中.

目的:调用委托(主持人)来解除(推送)UIViewController.
问题:无法访问委托的hello().

以下代码编译,但我得到一个运行时错误:未知的委托方法(见下文).

主机/呼叫(委托)对象:

import UIKit

class MainViewController: UIViewController, ProtocolNameDelegate {                     
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    // ---------------------------------------------------------------------------------------------------------------
    // Protocol Delegate

    func hello() {
        println("Hello");
    }

    // ---------------------------------------------------------------------------------------------------------------

    @IBAction func greenAction(sender : AnyObject) { 
        let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("GreenViewController") as GreenViewController
        secondViewController.delegate = self;
        self.presentViewController(secondViewController, animated: true, completion: nil)
    }

    // ---------------------------------------------------------------------------------------------------------------

    @IBAction func exitAction(sender : AnyObject) {
        exit(0)
    }

要被解雇的推送(第二个或“绿色”)UIViewController:

import UIKit

@class_protocol protocol ProtocolNameDelegate {
    func hello()
}

class GreenViewController: UIViewController {
    weak var delegate: ProtocolNameDelegate?

    // ---------------------------------------------------------------------------------------------------------------

    @IBAction func returnAction(sender : UIBarButtonItem) {
        println("Inside returnAction")
        delegate?.hello()
    }  
}

修订:更正了委托访问:delegate?.hello()…
并重新运行该应用程序.以下是通过调试器:

(lldb) po delegate
Some
 {
  Some = {
    payload_data_0 = 0x0d110b90 -> 0x00009a78 (void *)0x00009b70: OBJC_METACLASS_$__TtC9RicSwift218MainViewController
    payload_data_1 = 0x0d110b90 -> 0x00009a78 (void *)0x00009b70: OBJC_METACLASS_$__TtC9RicSwift218MainViewController
    payload_data_2 = 0x00000000
    instance_type = 0x00000000
  }
}
(lldb) po delegate.hello()
error: <REPL>:1:1: error: 'ProtocolNameDelegate?' does not have a member named 'hello'
delegate.hello()

(lldb) po delegate?.hello()
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0xb3145b0).
The process has been returned to the state before expression evaluation.

问题:我错过了什么或做错了什么?

最佳答案 这里的问题是委托是一个可选的.所以要访问它你应该这样做

delegate?.hello()

这样就可以打开可选项,如果它不是,则调用hello

ProtocolNameDelegate?是ProtocolNameDelegate的一个不同类型,特别是Optional.

点赞