- 代理模式
- 实现要点:
- 首先定义一个协议,协议中声明需要通信的方法。例如:
protocol PluginCommunicationProtocol {
func sendData(data: String)
}
- 在需要接收数据的插件模块中,定义一个遵循该协议的代理属性,并且实现协议方法。例如:
class ReceiverPlugin {
var delegate: PluginCommunicationProtocol?
func someFunction() {
delegate?.sendData(data: "Hello from Receiver")
}
}
- 在发送数据的插件模块中,设置代理为接收模块的实例,并调用代理方法发送数据。例如:
class SenderPlugin {
let receiver = ReceiverPlugin()
init() {
receiver.delegate = self
}
}
extension SenderPlugin: PluginCommunicationProtocol {
func sendData(data: String) {
print("Received data: \(data)")
}
}
- 通知中心(NotificationCenter)
- 实现要点:
- 在发送数据的插件模块中,使用
NotificationCenter.default.post
方法发送通知,并携带需要传递的数据。例如:
class SenderPlugin {
func sendData() {
let userInfo = ["data": "Some important data"]
NotificationCenter.default.post(name: Notification.Name("PluginDataNotification"), object: nil, userInfo: userInfo)
}
}
- 在接收数据的插件模块中,使用`NotificationCenter.default.addObserver`方法注册监听通知,并在回调方法中处理数据。例如:
class ReceiverPlugin {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(receiveData(_:)), name: Notification.Name("PluginDataNotification"), object: nil)
}
@objc func receiveData(_ notification: Notification) {
if let userInfo = notification.userInfo, let data = userInfo["data"] as? String {
print("Received data: \(data)")
}
}
}
- 闭包回调
- 实现要点:
- 在接收数据的插件模块中,定义一个闭包属性用于接收数据。例如:
class ReceiverPlugin {
var dataReceivedClosure: ((String) -> Void)?
func someFunction() {
dataReceivedClosure?("Data from Receiver")
}
}
- 在发送数据的插件模块中,设置闭包并在闭包中处理接收到的数据。例如:
class SenderPlugin {
let receiver = ReceiverPlugin()
init() {
receiver.dataReceivedClosure = { data in
print("Received data: \(data)")
}
}
}