我试图了解代理如何在Swift中运行得更好,总的来说。在我创建的示例中,我有一个Sender
类和一个Receiver
类。我想从Sender
向Receiver
然后,我想创建Receiver
类的变量实例,并打印Sender
发送给它的消息。但是当我从我创建的变量实例ShareMessage(message: NSString)
调用函数var recieveMessage
时,我遇到了困难,我必须输入另一个消息或字符串,我无法检索Sender
的消息发给它的课。
这是我正在使用的代码。我不确定我所询问的内容是否正确,但我对如何检索变量实例中的数据感到好奇。
import UIKit
// Protocol to send message between classes.
protocol SendersMessageDelegate{
func shareMessage(message: NSString)
}
// Class that sends the message
class Sender{
// Create variable to hold message
var sendersMessage: NSString = NSString()
var delegate: SendersMessageDelegate? = Receiver()
// Grab the message when initialized and send to delegate
init(sendersMessage: NSString){
self.sendersMessage = sendersMessage
delegate?.shareMessage(sendersMessage)
}
}
//Class receiving the message
class Receiver: SendersMessageDelegate{
func shareMessage(message: NSString) {
println(message)
}
}
//Create variable instance of sender and send message in initializer.
var sendMessage: Sender = Sender(sendersMessage: "Hello Receiver.")
var receiveMessage: Receiver = Receiver()
receiveMessage.shareMessage(message: NSString) <---- //Can't retrieve message as need new argument for function call.
我无法检索message
或数据,因为我必须传递一个新参数。
receiveMessage.shareMessage(message: NSString)
答案 0 :(得分:6)
我认为你的逻辑有些混乱。
您的发件人已设置为自行创建接收器,然后在创建时立即向其发送消息。
所以在这一行:
var sendMessage: Sender = Sender(sendersMessage: "Hello Receiver.")
您已经完成了接下来两行中您尝试做的事情。如果你想让这个接收器存储消息并让你稍后检索,那么你需要你的Receiver类将它保存为变量并打印出来。
class Receiver: SendersMessageDelegate{
var savedMessage:NSString?
func shareMessage(message: NSString) {
savedMessage = message
println(message)
}
}
然后您可以通过执行以下操作来访问:
var sharedMessage = receiver.savedMessage
然而,您遇到的第二个问题是,因为您已经在发件人中创建了接收器,所以您需要从接收器中拔出接收器。
var sender: Sender = Sender(sendersMessage: "Hello Receiver.")
var receiver:Receiver = sender.delegate
var sharedMessage = receiver.savedMessage
这是一件非常奇怪的事情。通常的模式是创建一个Receiver并将其提供给Sender。然后调用发件人中的一个函数,该函数将触发发送给Receiver的消息。像这样:
import UIKit
// Protocol to send message between classes.
protocol SendersMessageDelegate{
func shareMessage(message: NSString)
}
// Class that sends the message
class Sender{
// Create variable to hold message
var sendersMessage: NSString = NSString()
var delegate: SendersMessageDelegate?
// Save the message that it needs to send
init(sendersMessage: NSString){
self.sendersMessage = sendersMessage
}
// If it has as a delegate, then share the message with it.
func sendMessage() {
delegate?.shareMessage(sendersMessage)
}
}
//Class receiving the message
class Receiver: SendersMessageDelegate{
var savedMessage:NSString?
func shareMessage(message: NSString) {
savedMessage = message
println(message)
}
}
//Create Sender and Receiver
var sender: Sender = Sender(sendersMessage: "Hello Receiver.")
var receiver: Receiver = Receiver()
//give Sender it's Receiver
sender.delegate = receiver
//Trigger the sender to send message to it's Receiver
sender.sendMessage()