在不相关的视图控制器之间传递数据

Passing data between unrelated view controllers

如何在两个不同(不相关)的视图控制器之间传递数据?根据我对代表的理解,需要某种关系(例如,准备 segue 等)。我有一个显示搜索结果的单独视图控制器,我想在另一个屏幕中触发一个 table 视图,并使用一个单独的视图控制器滚动到该位置,并突出显示该行。为此,我需要让 table 视图知道要突出显示的内容。

为此,您可以使用 NSNotificationCenter (Apple Docs)

简而言之,在接收viewController中,你在viewDidLoad中声明了一个观察者:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "actOnSpecialNotification", name: "myNotification", object: nil)

和相应的函数被调用

func actOnSpecialNotification() {
    self.notificationLabel.text = "I heard the notification"
}

当您需要向 viewController 发送消息时,在您的发送 viewController 中发送以下消息:

NSNotificationCenter.defaultCenter().postNotificationName("myNotification", object: self)

有关更多信息,我邀请您查看 Andrew Bancroft 制作的这个制作精良的教程:The Tutorial

除了已经提到的通知之外,您还可以使用 appDelegate 访问全局变量:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable

一个更简单的方法是在消费者控制器中使用一个静态成员,然后在生产者控制器中设置它。当消费者控制器激活时,您可以使用数据并清除它,以便下次不再使用它。这种方法的一个优点是它将视图控制器所需的数据保存在自身内部,而不是分布在应用程序中,例如在使用全局变量时。