【发布时间】:2015-01-09 16:43:20
【问题描述】:
我正在尝试模拟使用 Swift 访问对象委托的 Objective-C 模式。通常我会将协议放在两个 UIViewController 之间共享的 .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.
问题:我错过了什么或做错了什么?
【问题讨论】: