在我的ViewController(VC1)中,我具有以下变量:
var orderInfo: Order!
Order本身是一个结构,如下所示:
struct Order {
var orderId: String
var orderReferenceNumber: String
//more variables...
init(
orderId: String,
orderReferenceNumber: String,
){
self.orderId = orderId
self.orderReferenceNumber = orderReferenceNumber
}
init(data: [String: Any]){
orderId = data[DatabaseRef.orderId] as? String ?? ""
orderReferenceNumber = data[DatabaseRef.orderReferenceNumber] as? String ?? ""
}
static func modelToData(order: Order) -> [String: Any] {
let data : [String: Any] = [
DatabaseRef.orderId: order.orderId,
DatabaseRef.orderReferenceNumber: order.orderReferenceNumber,
]
return data
}
}
在VC1中,我有一个侦听器,该侦听器从Firestore数据库(通过Addsnapshotslistener)更新其信息。当由于数据库顺序的更改而在VC1中更新变量orderInfo
时,侦听器将更新VC1中的orderInfo
变量。当用户在另一个ViewController(例如VC2)中时,我想使用VC1中的更新信息来访问orderInfo
变量。我怎样才能做到这一点?
有许多种方法可以做到这一点。让我们提及其中的一些。
示例
class VC1: UIViewController {
var orderInfo: Order!
func updateOrder() {
var orderDict = ["orderInfo":orderInfo]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "orderInfoUpdated"), object: nil, userInfo: orderDict)
}
}
// The receiving end
class VC2: UIViewController {
var orderInfo: Order!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(doSomething(_: )), name: NSNotification.Name(rawValue: "orderInfoUpdated"), object: nil)
}
func doSomething(_ notification: NSNotification) {
if let orderInfo = notification.userInfo?["orderInfo"] as? Order {
// Do something
}
}
}
示例:
class AppState {
static let shared = AppState()
var orderInfo: Order!
...
}
在您的ViewController上
class ViewController: UIViewController {
func doSomeWork() {
print(AppState.shared.orderInfo)
}
}